// 语句块

function AddMotorbitCode(Blockly) {

  Blockly.Python.microbitStart = function (block) {
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    let n = 0;
      let code = '';
      let branchCode;
      if (block.getInput('SUBSTACK0')) {
          branchCode = Blockly.Python.statementToCode2(block, 'SUBSTACK0');
          code += `\n${branchCode}\n`;
      }
     
      return `${code}`;
  }
  
  Blockly.Python.microbitLoop = function (block) {
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      const until = block.getFieldValue('MODE') == 'UNTIL';
      let argument0 = Blockly.Python.valueToCode(block, 'BOOL',
        until ? Blockly.Arduino.ORDER_LOGICAL_NOT :
          Blockly.Python.ORDER_NONE) || 'True';
      let branch = Blockly.Python.statementToCode(block, 'SUBSTACK0');
      branch = Blockly.Python.addLoopTrap(branch, block.id) ||
        Blockly.Python.PASS;
      if (until) {
        argument0 = `!${argument0}`;
      }
      return `while ${argument0}: \ncodeLine1111\n${branch}\n`;

  }
  
  
  Blockly.Python.microbitButton = function (block) {
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    var button = block.getFieldValue('buttonEvent');
    let n = 0;
    var code = '';
    let branchCode;
    var funcName = '';
    var funcStr = "";
    if (block.getInput('SUBSTACK0')) {
      branchCode = Blockly.Python.statementToCode2(block, 'SUBSTACK0');
      code = code + '  ' +  `${branchCode}\n`;
    }
    // code = code.replace(/\s+/g,"  ");
    let codeArr = code.split("\n");
    var code1 =  "";
    for(let i = 0 ; i < codeArr.length; i++) {
        code1 = code1 + "  " + codeArr[i] + "\n";
    }
    code1 = code1.trim();
    var codeResult = code.length == 0?'  pass':'  '+ code1;
    var buttonCode = '';
    if(button === "a"){
        funcStr = 'func_button_a';
        funcName = 'func_button_a=on_button_a()';
        buttonCode = 'def on_button_a():\n'+
        '  while True:\n'+
        '    if button_a.is_pressed() and not button_b.is_pressed():\n'+
        '      yield callback_button_a()\n'+
        '    else:\n'+
        '      yield\n'+
        'def callback_button_a():\n'+
        '  global em_n_my_float_variable, em_s_my_string_variable\n'
        + codeResult;
      }else if(button === "b"){
        funcStr = 'func_button_b';
        funcName = 'func_button_b=on_button_b()';
        buttonCode = 'def on_button_b():\n'+
        '  while True:\n'+
        '    if button_b.is_pressed() and not button_a.is_pressed():\n'+
        '      yield callback_button_b()\n'+
        '    else:\n'+
        '      yield\n'+
        'def callback_button_b():\n'+
        '  global em_n_my_float_variable, em_s_my_string_variable\n'
        + codeResult;
      }else{
        funcStr = 'func_button_ab';
        funcName = 'func_button_ab=on_button_ab()';
        buttonCode = 'def on_button_ab():\n'+
        '  while True:\n'+
        '    if button_a.is_pressed() and  button_b.is_pressed():\n'+
        '      yield callback_button_ab()\n'+
        '    else:\n'+
        '      yield\n'+
        'def callback_button_ab():\n'+
        '  global em_n_my_float_variable, em_s_my_string_variable\n'
        + codeResult;
      }
    Blockly.Python.definitions_['import_microbitDef'+button] = buttonCode;
    return funcName+'\n';
  }
  
  
   Blockly.Python.statementToCode2 = function(block, name) {
    var targetBlock = block.getInputTargetBlock(name);
    var code = Blockly.Python.blockToCode(targetBlock);
    return code;
  };
  
    
  
  
    // Blockly.Python.control_start = function (block) {
    //   Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    //   return '';
    // };
  
    //显示数字
    Blockly.Python.displayShowNumber = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var number = Blockly.Python.valueToCode(this, 'displayShowNumber', Blockly.Arduino.ORDER_ATOMIC);
      return 'display.scroll(' + number + ')\n';
    };
  
    //显示图片
    Blockly.Python.displayShowImageView = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var image = block.getFieldValue('image');
      return 'display.show(' + image + ')\n';
    };
  
    //显示字符串
    Blockly.Python.displayShowString = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var string = Blockly.Python.valueToCode(this, 'displayShowString', Blockly.Arduino.ORDER_ATOMIC);
      return 'display.scroll(str(' + string.replace(/'/g, '') + '))\n';
    };
  
    //暂停   睡眠
    Blockly.Python.pauseSleep = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      // var time = block.getFieldValue('time');
      var sleepTime = Blockly.Python.valueToCode(this, 'sleepTime', Blockly.Arduino.ORDER_ATOMIC);
      return 'sleep(' + sleepTime + ')\n';
    };
  
    //清除屏幕
    Blockly.Python.emptyScreen = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      return 'display.clear()\n';
    };
  
    //显示方向
    Blockly.Python.displayShowArrow = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var displayShowArrow = block.getFieldValue('displayShowArrow');
      return 'display.show(' + displayShowArrow + ')\n';
    };
  
    //当按钮被按下
    Blockly.Python.buttonPressed = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var Button = block.getFieldValue('Button');
      var cod = '';
      if (Button === 'A') {
        cod = 'if button_a.is_pressed():'
      } else if (Button === 'B') {
        cod = 'if button_b.is_pressed():'
      } else if (Button === 'A+B') {
        cod = 'if button_a.is_pressed() and button_b.is_pressed():'
      }
      var code = 'while True:';
      var branch = Blockly.Python.statementToCode(this, 'DO');
      branch = Blockly.Python.addLoopTrap(branch, block.id) ||
        Blockly.Python.PASS;
      var code2 = `${cod} \n${branch}\n`;
      // Blockly.Python.definitions_['func_timer'] = code2;
      return code2;
    };
  
    // var branch = Blockly.Python.statementToCode(block, 'SUBSTACK');
    //   branch = Blockly.Python.addLoopTrap(branch, block.id) ||
    //     Blockly.Python.PASS;
    //   var loopVar = Blockly.Python.variableDB_.getDistinctName(
    //     'count', Blockly.Variables.NAME_TYPE);
    //   var code = 'for ' + loopVar + ' in range(' + repeats + '):\n' + branch;
    //   return code;
  
    //当微标朝上
    Blockly.Python.stateChange = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var Button = block.getFieldValue('state');
      console.log(Button)
      var cod = '';
      if (Button == 'shock') {
        cod = 'if accelerometer.was_gesture("shake"):'
      } else if (Button == 'up') {
        cod = 'if accelerometer.was_gesture("up"):'
      } else if (Button == 'down') {
        cod = 'if accelerometer.was_gesture("down"):'
      } else if (Button == 'left') {
        cod = 'if accelerometer.was_gesture("left"):'
      } else if (Button == 'right') {
        cod = 'if accelerometer.was_gesture("right"):'
      } else if (Button == 'screenup') {
        cod = 'if accelerometer.was_gesture("face up"):'
      } else if (Button == 'screendown') {
        cod = 'if accelerometer.was_gesture("face down"):'
      } else if (Button == 'fall') {
        cod = 'if accelerometer.was_gesture("freefall"):'
      } else if (Button == '3g') {
        cod = 'if accelerometer.was_gesture("3g"):'
      } else if (Button == '6g') {
        cod = 'if accelerometer.was_gesture("6g"):'
      } else if (Button == '8g') {
        cod = 'if accelerometer.was_gesture("8g"):'
      }
      var code = 'while True:';
      var branch = Blockly.Python.statementToCode(this, 'DO');
      branch = Blockly.Python.addLoopTrap(branch, block.id) ||
        Blockly.Python.PASS;
      var code2 = `${cod} \n${branch}\n`;
      // Blockly.Python.definitions_['func_timer'] = code2;
      return code2;
    };
  
    //当引脚被按下
    Blockly.Python.pinTouched = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var pin = block.getFieldValue('Pin');
      var cod = '';
      if (pin === 'p0') {
        cod = 'if pin0.is_touched():'
      } else if (pin === 'p1') {
        cod = 'if pin1.is_touched():'
      } else if (pin === 'p2') {
        cod = 'if pin2.is_touched():'
      }
      var code = 'while True:';
      var branch = Blockly.Python.statementToCode(this, 'DO');
      branch = Blockly.Python.addLoopTrap(branch, block.id) ||
        Blockly.Python.PASS;
      var code2 = `${cod} \n${branch}\n`;
      // Blockly.Python.definitions_['func_timer'] = code2;
      return code2;
    };
  
    //按钮是否被按下  
    Blockly.Python.buttonPressedTowState = function (block) {
      var Button = block.getFieldValue('Button');
      var cod = '';
      if (Button === 'A') {
        cod = 'button_a.is_pressed()'
      } else if (Button === 'B') {
        cod = 'button_b.is_pressed()'
      } else if (Button === 'A+B') {
        cod = 'button_a.is_pressed() and button_b.is_pressed()'
      }
      return [cod, Blockly.Python.ORDER_ATOMIC];
    };
  
    
  
    //引脚是否被接通
    Blockly.Python.pinPressedTowState = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var pin = block.getFieldValue('PinState');
      var cod = '';
      if (pin === 'p0') {
        cod = 'pin0.is_touched()'
      } else if (pin === 'p1') {
        cod = 'pin1.is_touched()'
      } else if (pin === 'p2') {
        cod = 'pin2.is_touched()'
      }
      return [cod, Blockly.Python.ORDER_ATOMIC]
    };
  
    //加速度
    Blockly.Python.accelerationValue = function (block) {
      var acceleration = block.getFieldValue('acceleration');
      var cod = '123'
      if (acceleration == 'x') {
        cod = 'accelerometer.get_x()'
      } else if (acceleration == 'y') {
        cod = 'accelerometer.get_y()'
      } else if (acceleration == 'z') {
        cod = 'accelerometer.get_z()'
      }
      return [cod, Blockly.Python.ORDER_ATOMIC];
    };
  
  
    //亮度级别
    Blockly.Python.brightnessLevel = function (block) {
      return ['display.get_pixel(2, 2)', Blockly.Python.ORDER_ATOMIC];
    };
  
    //指南针朝向
    Blockly.Python.pointerOrientation = function (block) {
      return ['compass.heading()', Blockly.Python.ORDER_ATOMIC]
    };
  
    //温度
    Blockly.Python.temperaTure = function (block) {
      return ['temperature()', Blockly.Python.ORDER_ATOMIC]
    };
  
    //旋转方式
    Blockly.Python.rotationMode = function (block) {
      var pin = block.getFieldValue('rotation');
      var cod = '';
      if (pin == 'rotate') {
        cod = 'accelerometer.get_y()'
      } else if (pin == 'roll') {
        cod = 'accelerometer.get_x()'
      }
      return [cod, Blockly.Python.ORDER_ATOMIC]
    };
  
  
    //磁力
    Blockly.Python.magneticForce = function (block) {
      var acceleration = block.getFieldValue('magnetic');
      var cod = '123'
      if (acceleration == 'x') {
        cod = 'compass.get_x()'
      } else if (acceleration == 'y') {
        cod = 'compass.get_y()'
      } else if (acceleration == 'z') {
        cod = 'compass.get_z()'
      }
      return [cod, Blockly.Python.ORDER_ATOMIC]
    };
  
    //运行时间
    Blockly.Python.runningTime = function (block) {
      //return 'display.scroll(' + string.replace(/'/g, '"') + ')\n';
      return ['running_time()', Blockly.Python.ORDER_ATOMIC]
    };
  
    //校准指南针
    Blockly.Python.calibrateCompass = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      return 'compass.calibrate()\n';
    };
  
    //当引脚被释放时  
    Blockly.Python.pinPressedThreeState = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var pin = block.getFieldValue('State');
      var cod = '';
      if (pin === 'p0') {
        cod = 'while pin0.is_touched():\n' + "    " + 'sign = 1\n' + "  " + 'if sign == 1:\n' + "    " + 'sign = 0 '
      } else if (pin === 'p1') {
        cod = 'while pin1.is_touched():\n' + "    " + 'sign = 1\n' + "  " + 'if sign == 1:\n' + "    " + 'sign = 0 '
      } else if (pin === 'p2') {
        cod = 'while pin2.is_touched():\n' + "    " + 'sign = 1\n' + "  " + 'if sign == 1:\n' + "    " + 'sign = 0 '
      }
      var code = 'while True:';
      var branch = Blockly.Python.statementToCode(this, 'DO');
      branch = Blockly.Python.addLoopTrap(branch, block.id) ||
        Blockly.Python.PASS;
      var code2 = `${cod} \n${branch}\n`;
      // Blockly.Python.definitions_['func_timer'] = code2;
      return code2;
    };
  
    //Music
    //播放音调 playTone
    Blockly.Python.playTone = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitmusic'] = 'import music';
      var tone = block.getFieldValue('tone');
      var rhythm = block.getFieldValue('rhythm');
      var playPin = block.getFieldValue('playPin');
      rhythm = parseInt(rhythm * 500);
      return 'music.pitch(' + tone + ',' + rhythm + ','+ playPin +')\n';
    };
  
    //播放铃声
    Blockly.Python.playRingTone = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitmusic'] = 'import music';
      var tone = block.getFieldValue('tone');
      var playPin = block.getFieldValue('playPin');
      return 'music.pitch(' + tone +','+ playPin + ',-1)\n';
    };
  
    //暂停播放（ms）
    Blockly.Python.pausePlayback = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitmusic'] = 'import music';
      var rhythm = block.getFieldValue('rhythm');
      rhythm = rhythm * 500;
      rhythm = parseInt(rhythm);
      return 'music.pitch(0,' + rhythm + ')\n';
    };
  
    //播放旋律
    Blockly.Python.playMelody = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitmusic'] = 'import music';
      var song = block.getFieldValue('song');
      var playPin = block.getFieldValue('playPin');
      var frequency = block.getFieldValue('frequency');
      var code = "";
      if (frequency == "once") {
        code = 'for i in range(1):\n music.play(' + song + ','+ playPin +')\n';
      } else if (frequency == "loop") {
        code = 'while True:\n music.play(' + song + ','+ playPin + ')\n';
      }
      return code;
    };
  
    //palyTime
    Blockly.Python.palyTime = function (block) {
      return 'null\n';
    };
  
    //stopMelody
    Blockly.Python.stopMelody = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitmusic'] = ' import music';
      var stopPin = block.getFieldValue('stopPin');
      return 'music.stop('+ stopPin +')\n';
    };
  
    //tone
    Blockly.Python.tone = function (block) {
      var tone = block.getFieldValue('tone');
      return tone;
    };
  
    //rhythm
    Blockly.Python.rhythm = function (block) {
      var rhythm = block.getFieldValue('rhythm');
      return rhythm;
    };
  
    //bpm
    Blockly.Python.bpm = function (block) {
      return 'bpm';
    };
  
    //将节奏更改为（bpm）
    Blockly.Python.bpmChange = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitmusic'] = 'import music';
      var bpm = Blockly.Python.valueToCode(this, 'bpm', Blockly.Arduino.ORDER_ATOMIC);
      if (bpm <= 0) {
        bpm = 20;
      }
      return 'music.set_tempo(bpm = ' + bpm + ')\n';
    };
  
    //将节奏设定为（bpm）
    Blockly.Python.bpmSetting = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitmusic'] = 'import music';
      var bpm = Blockly.Python.valueToCode(this, 'bpm', Blockly.Arduino.ORDER_ATOMIC);
      if (bpm <= 0) {
        bpm = 120;
      }
      bpm = parseInt(bpm);
      return 'music.set_tempo(bpm = ' + bpm + ')\n';
    };
  
    //LED
    //绘图
    lightlevel = 9;
    Blockly.Python.drawing = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var x = Blockly.Python.valueToCode(this, 'x', Blockly.Arduino.ORDER_ATOMIC);
      var y = Blockly.Python.valueToCode(this, 'y', Blockly.Arduino.ORDER_ATOMIC);
      return 'display.set_pixel(' + x + ',' + y + ','+ lightlevel +')\n';
  
    };
  
    //取消绘图
    Blockly.Python.cancelMapping = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var x = Blockly.Python.valueToCode(this, 'x', Blockly.Arduino.ORDER_ATOMIC);
      var y = Blockly.Python.valueToCode(this, 'y', Blockly.Arduino.ORDER_ATOMIC);
      return 'display.set_pixel(' + x + ',' + y + ',0)\n';
    };
  
    //切换绘图
    Blockly.Python.switchMapping = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var x = Blockly.Python.valueToCode(this, 'x', Blockly.Arduino.ORDER_ATOMIC);
      var y = Blockly.Python.valueToCode(this, 'y', Blockly.Arduino.ORDER_ATOMIC);
      return 'if display.get_pixel(' + x + ',' + y + '):\n display.set_pixel(' + x + ',' + y + ',0)\nelse:\n display.set_pixel(' + x + ',' + y + ','+ lightlevel +') \n';
    };
  
    //点图
    Blockly.Python.spotMapping = function (block) {
      var x = Blockly.Python.valueToCode(this, 'x', Blockly.Arduino.ORDER_ATOMIC);
      var y = Blockly.Python.valueToCode(this, 'y', Blockly.Arduino.ORDER_ATOMIC);
      var code = 'display.get_pixel(' + x + ',' + y + ')';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //绘制条形图
    Blockly.Python.drawBarType = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var x = Blockly.Python.valueToCode(this, 'x', Blockly.Arduino.ORDER_ATOMIC);
      var y = Blockly.Python.valueToCode(this, 'y', Blockly.Arduino.ORDER_ATOMIC);
      //return 'display.get_pixel(' + x + ',' + y + ')\n';
      return 'line = [2, 1, 3, 0, 4]\nrow = [4, 3, 2, 1, 0]\ndef bar_chart(variable, highest):\n  sign, line_GPS, row_GPS= 1, 0, 0\n  for i in range(0, min([variable, highest])*10000, (highest*10000)//15):\n    ' +
        'if row_GPS == 5:\n      break\n    if sign:\n      sign = 0\n      display.set_pixel(2, row[row_GPS], '+ lightlevel +')\n      line_GPS += 1\n    else:\n      for j in range(2):\n        ' +
        'display.set_pixel(line[line_GPS], row[row_GPS], '+ lightlevel +')\n        line_GPS += 1\n    if line_GPS == 5:\n      line_GPS = 0\n      row_GPS += 1\n      sign = 1\n  for i in range(row_GPS, 5):\n    ' +
        'for j in range(line_GPS, 5):\n      display.set_pixel(line[j], row[i], 0)\n    line_GPS = 0\n  sleep(50)\nbar_chart(' + x + ', ' + y + ')\n';
    };
  
    //绘图 加入亮度条件
    Blockly.Python.drawingLight = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var x = Blockly.Python.valueToCode(this, 'x', Blockly.Arduino.ORDER_ATOMIC);
      var y = Blockly.Python.valueToCode(this, 'y', Blockly.Arduino.ORDER_ATOMIC);
      var brightness = Blockly.Python.valueToCode(this, 'brightness', Blockly.Arduino.ORDER_ATOMIC);
      return 'display.set_pixel(' + x + ',' + y + ',' + brightness + ')\n';
    };
  
    //亮度
    Blockly.Python.brightness = function (block) {
      if (lightlevel != null) {
        return [lightlevel, Blockly.Python.ORDER_ATOMIC]
      }
      return ["ERROR", Blockly.Python.ORDER_ATOMIC];
    };
  
    //设置亮度
    Blockly.Python.setBrightness = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      lightlevel = Blockly.Python.valueToCode(this, 'brightness', Blockly.Arduino.ORDER_ATOMIC);
      if(lightlevel>9){
        lightlevel = 9;
      }else if(lightlevel < 0){
        lightlevel = 0;
      }
      return 'lightlevel = ' + lightlevel + '\n';
    };
  
    //停止动画
    Blockly.Python.stopAnimation = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      return 'display.clear()\n';
    };
  
    //LED启用
    Blockly.Python.LEDEnabled = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var boolean_ = block.getFieldValue('boolean_');
      if (boolean_ == "true") {
        lightlevel = 8;
      } else {
        lightlevel = 0;
      }
      return '';
    };
  
    //wifi
    //无线设置组
    Blockly.Python.wifiSetting = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitRadio'] = 'import radio';
      var setWifi = Blockly.Python.valueToCode(this, 'setWifi', Blockly.Arduino.ORDER_ATOMIC);
      return 'radio.config(channel=' + setWifi + ')\n';
    };
  
    //打开无线设置组
    Blockly.Python.openWifi = function (block) {
     Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
     Blockly.Python.definitions_['import_microbitRadio'] = 'import radio';
     var wifiSwitch =block.getFieldValue('wifiSwitch'); 
     return 'radio.' + wifiSwitch + '\n';
   };
    //无线发送数字
    Blockly.Python.wifiSendNumber = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitRadio'] = 'import radio';
      // Blockly.Python.definitions_['import_microbitOnRadio'] = 'radio.on()';
      var setWifiNumber = Blockly.Python.valueToCode(this, 'setWifiNumber', Blockly.Arduino.ORDER_ATOMIC);
      // setWifiNumber = setwifiString.replace(/"/g, '');
      return 'radio.send("' + setWifiNumber + '")\n';
    };
  
    //无线发送字符串
    Blockly.Python.wifiSettingString = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitRadio'] = 'import radio';
      // Blockly.Python.definitions_['import_microbitOnRadio'] = 'radio.on()';
      var setwifiString = Blockly.Python.valueToCode(this, 'setwifiString', Blockly.Arduino.ORDER_ATOMIC);
      setwifiString = setwifiString.replace(/'/g,"");
      // setwifiString =  setwifiString.replace(/"/g, '') ;
      return 'radio.send(' + setwifiString + ')\n';
    };
  
  
    //无线发送值
    Blockly.Python.wifiSettingValue = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitRadio'] = 'import radio';
      // Blockly.Python.definitions_['import_microbitOnRadio'] = 'radio.on()';
      var setWifiName = Blockly.Python.valueToCode(this, 'setWifiName', Blockly.Arduino.ORDER_ATOMIC);
      var setWifiValue = Blockly.Python.valueToCode(this, 'setWifiValue', Blockly.Arduino.ORDER_ATOMIC);
      return 'radio.send(' + setWifiName.replace(/"/g, '') + '+' + setWifiValue + ')\n';
    };
  
    Blockly.Python.receivingData = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitRadio'] = 'import radio';
      // Blockly.Python.definitions_['import_microbitOnRadio'] = 'radio.on()';
      var code = 'radio.receive()';
      return [code, Blockly.Python.ORDER_ATOMIC];
    };
    
    //在无线接收到数据时运行 receivedNumber
    Blockly.Python.receivingDataStatusOne = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitRadio'] = 'import radio';
      // Blockly.Python.definitions_['import_microbitOnRadio'] = 'radio.on()';
      var cod = 'receivedNumber=radio.receive()\nif receivedNumber = ‘6’:';
      var branch = Blockly.Python.statementToCode(this, 'DO');
      var code2 = `${cod} \n ${branch}\n`;
      return code2;
    };
  
    //在无线接收到数据时运行 receivedNumber
    Blockly.Python.receivingDataStatusTwo = function (block) {
      Blockly.Python.definitions_['import_microbitOnRadio'] = 'radio.on()';
      var cod = 'incoming=radio.receive()\nif incoming = ‘microbit123’:';
      var branch = Blockly.Python.statementToCode(this, 'DO');
      var code2 = `${cod} \n ${branch}\n`;
      return code2;
    };
  
    //在无线接收到数据时运行 receivedNumber
    Blockly.Python.receivingDataStatusThree = function (block) {
      Blockly.Python.definitions_['import_microbitOnRadio'] = 'radio.on()';
      var cod = 'if receivedString = ‘microbit’: ';
      var branch = Blockly.Python.statementToCode(this, 'DO');
      var code2 = `${cod} \n ${branch}\n`;
      return code2;
    };
  
    //接收到的数据包
    Blockly.Python.packetsReceived = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitRadio'] = 'import radio';
      Blockly.Python.definitions_['import_microbitRadio'] = 'import time';
      // Blockly.Python.definitions_['import_microbitOnRadio'] = 'radio.on()';
      var acceleration = block.getFieldValue('magnetic');
      var code = 'if radio.receive():\n whentime = time.ticks_ms()';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //无线设置发射功率 power
    Blockly.Python.wifiTansmitPower = function (block) {
      var power = block.getFieldValue('power');
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitRadio'] = 'import radio';
      Blockly.Python.definitions_['import_microbitOnRadio'] = 'radio.on()';
      // var power = Blockly.Python.valueToCode(this, 'power', Blockly.Arduino.ORDER_ATOMIC);
      return 'radio.config(power= ' + power + ')\n';
    };
  
    //数学
    //initData
    Blockly.Python.initData = function (block) {
      var data = Blockly.Python.valueToCode(this, 'data', Blockly.Arduino.ORDER_ATOMIC);
      return [parseInt(data)];
    };
  
    //余数
    Blockly.Python.remainder = function (block) {
      var data1 = Blockly.Python.valueToCode(this, 'data1', Blockly.Arduino.ORDER_ATOMIC);
      var data2 = Blockly.Python.valueToCode(this, 'data2', Blockly.Arduino.ORDER_ATOMIC);
      var result = ''+data1+' % '+data2+'';
      return [result, Blockly.Python.ORDER_ATOMIC];
    };
  
    //两个数间的最大值于最小值
    Blockly.Python.betweenNumbers = function (block) {
      var most = block.getFieldValue('most');
      var data1 = Blockly.Python.valueToCode(this, 'data1', Blockly.Arduino.ORDER_ATOMIC);
      var data2 = Blockly.Python.valueToCode(this, 'data2', Blockly.Arduino.ORDER_ATOMIC);
      data1 = parseInt(data1);
      data2 = parseInt(data2);
      var result = "";
      if (most == "min") {
        // if (data1 > data2) {
        //   result = data2 + 1;
        // } else {
        //   result = data1 + 1;
        // }
        result = 'min('+data1+', '+data2+')'
      } else if (most == "max") {
        // if (data1 > data2) {
        //   result = data1 - 1;
        // } else {
        //   result = data2 - 1;
        // }
        result = 'max('+data1+', '+data2+')'
      }
      // if (data2 == data1) {
      //   result = data1;
      // }
      return [result, Blockly.Python.ORDER_ATOMIC];
    };
  
    //绝对值
    Blockly.Python.absoluteValue = function (block) {
      var data = Blockly.Python.valueToCode(this, 'absolute', Blockly.Arduino.ORDER_ATOMIC);
      data = parseInt(data.replace(/'/g, ''));
      var result = Math.abs(data);
      result = 'abs('+data+')';
      return [result, Blockly.Python.ORDER_ATOMIC];
    };
  
    //平方根
    Blockly.Python.squareRoot = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_math'] = 'import math';
      var data = Blockly.Python.valueToCode(this, 'data', Blockly.Arduino.ORDER_ATOMIC);
      var type = block.getFieldValue('type');
      var result = '';
      if(type == 'sqrt'){
        result = 'math.sqrt('+data+') ';
      }else if(type == 'sin'){
        result = 'math.sin('+data+') ';
      }else if(type == 'cos'){
        result = 'math.cos('+data+') ';
      }else if(type == 'tan'){
        result = 'math.tan('+data+') ';
      }else if(type == 'atan2'){
        result = 'math.atan2('+data+') ';
      }
      return [result, Blockly.Python.ORDER_ATOMIC];
    };
  
    //选取随机数
  Blockly.Python.selectRandomNumber = function (block) {
    Blockly.Python.definitions_['import_random'] = 'import random';
    var data1 = Blockly.Python.valueToCode(this, 'data1', Blockly.Arduino.ORDER_ATOMIC);
    var data2 = Blockly.Python.valueToCode(this, 'data2', Blockly.Arduino.ORDER_ATOMIC);
    data1 = parseInt(data1);
    data2 = parseInt(data2);
    var max = "";
    var min = "";
    if (data1 > data2) {
      max = data1;
      min = data2;
    } else {
      max = data2
      min = data1;
    }
    var Range = max - min;
    var Rand = Math.random();
    var result = "random.randint("+ min + ", " + max +")";   
    return [result, Blockly.Python.ORDER_ATOMIC];
  };
  
    //随机选取true或者false
    Blockly.Python.randomBoolean = function (block) {
      var randomNumber = Math.floor(Math.random() * (100 - 0)) + 0;
      var result = ""
      if (randomNumber % 2 == 1) {
        result = 'True';
      } else {
        result = 'False';
      }
      return [result, Blockly.Python.ORDER_ATOMIC];
    };
    
     //
    Blockly.Python.transferInt = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var data = Blockly.Python.valueToCode(this, 'data', Blockly.Python.ORDER_ATOMIC);
      var result = 'int(' + data + ')';
      return [result, Blockly.Python.ORDER_ATOMIC];
    };

    //数组
    //返回数组长度
    Blockly.Python.listLength = function (block) {
      var code = 'len()';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //从数组 L 中取得索引 5 的值
    Blockly.Python.getListIndexValue = function (block) {
      var index = Blockly.Python.valueToCode(this, 'index', Blockly.Arduino.ORDER_ATOMIC);
      var code = 'L(' + index + ')';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //将数组 L 中索引为0 的值设置为 4
    Blockly.Python.setListIndexValue = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var index = Blockly.Python.valueToCode(this, 'index', Blockly.Arduino.ORDER_ATOMIC);
      var value = Blockly.Python.valueToCode(this, 'value', Blockly.Arduino.ORDER_ATOMIC);
      return 'L.pop(' + index + ')\nL.insert(' + index + ',' + value + ')\n';
    };
  
    //添加值到list中
    Blockly.Python.addValueToList = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var value = Blockly.Python.valueToCode(this, 'value', Blockly.Arduino.ORDER_ATOMIC);
      return 'L.append(' + value + ')\n';
    };
  
    //获取并移除数组中最后一个值
    Blockly.Python.removeEndValue = function (block) {
      var code = 'L.pop()';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //查找某个值在数组中的下标
    Blockly.Python.getValuePosition = function (block) {
      var value = Blockly.Python.valueToCode(this, 'value', Blockly.Arduino.ORDER_ATOMIC);
      var code = 'L.index(' + value + ')';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //获取并移除 L 中的第一个值
    Blockly.Python.removeStartValue = function (block) {
      var code = 'L.pop(0)';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //L 在开头插入 5
    Blockly.Python.addValueToListHead = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var value = Blockly.Python.valueToCode(this, 'value', Blockly.Arduino.ORDER_ATOMIC);
      return 'L.insert(0,' + value + ')\n';
    };
  
    //L 在 0 处插入值  5
    Blockly.Python.addValueToListPosition = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var index = Blockly.Python.valueToCode(this, 'index', Blockly.Arduino.ORDER_ATOMIC);
      var value = Blockly.Python.valueToCode(this, 'value', Blockly.Arduino.ORDER_ATOMIC);
      return 'L.insert(' + index + ',' + value + ')\n';
    };
  
    //L移除 2 处的值
    Blockly.Python.removePositionValue = function (block) {
      var index = Blockly.Python.valueToCode(this, 'index', Blockly.Arduino.ORDER_ATOMIC);
      var code = 'L.pop(' + index + ')';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //L移除 2 处的值
    Blockly.Python.nullValue = function (block) {
      var code = 'L = []\n';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //文本
  
    //空值s
    Blockly.Python.nullValue = function (block) {
      var inputText = Blockly.Python.valueToCode(this, 'inputText', Blockly.Arduino.ORDER_ATOMIC);
      inputText = inputText.replace(/'/g,"");
      return [inputText, Blockly.Python.ORDER_ATOMIC]
    };
  
    //返回字符的长度
    Blockly.Python.returnStringLength = function (block) {
      var inputText = Blockly.Python.valueToCode(this, 'inputText', Blockly.Arduino.ORDER_ATOMIC);
      var code = 'len(' + inputText + ')';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //比较两个字符串 string_compare(' + inputText1 + ',' + inputText2 + ')
    Blockly.Python.comparativeText = function (block) {
      var inputText1 = Blockly.Python.valueToCode(this, 'inputText1', Blockly.Arduino.ORDER_ATOMIC);
      var inputText2 = Blockly.Python.valueToCode(this, 'inputText2', Blockly.Arduino.ORDER_ATOMIC);
      var code = 'def string_compare(str_one, str_two):\n'+
      '    if str_one > str_two:\n'+
      '        return 1\n'+
      '    elif str_one < str_two:\n'+
      '        return -1\n'+
      '    else:\n'+
      '        return 0\n';
      Blockly.Python.definitions_['import_textFuncDef'] = code;
      var result = 'string_compare(' + inputText1 + ',' + inputText2 + ')';
      return [result, Blockly.Python.ORDER_ATOMIC];
      // 
    };
  
    //获取字符串中的一部分 
    Blockly.Python.getSubString = function (block) {
      var startPosition = Blockly.Python.valueToCode(this, 'startPosition', Blockly.Arduino.ORDER_ATOMIC);
      var length = Blockly.Python.valueToCode(this, 'length', Blockly.Arduino.ORDER_ATOMIC);
      var inputText = Blockly.Python.valueToCode(this, 'inputText', Blockly.Arduino.ORDER_ATOMIC);
      inputText = inputText.replace(/'/g,"");
      var code = inputText+'[' + startPosition + ':' + length + ']';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //判断字符串是否为空
    Blockly.Python.isEmptyText = function (block) {
      var inputText = Blockly.Python.valueToCode(this, 'inputText', Blockly.Arduino.ORDER_ATOMIC);
      //return inputText.replace(/ /g, "") == ""?true:false;
      inputText = inputText.replace(/'/g,"");
      var code = 'not ' + inputText + '.strip()';
      return [code, Blockly.Python.ORDER_ATOMIC]
    }
  
    //将字符串转化为number类型
    Blockly.Python.parseToNumber = function (block) {
      var inputText = Blockly.Python.valueToCode(this, 'inputText', Blockly.Arduino.ORDER_ATOMIC);
      inputText = inputText.replace(/'/g,"");
      var code = 'int(' + inputText + ')';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //获取字符串中的一部分
    Blockly.Python.getIndexChar = function (block) {
      var inputText = Blockly.Python.valueToCode(this, 'inputText', Blockly.Arduino.ORDER_ATOMIC);
      var startPosition = Blockly.Python.valueToCode(this, 'startPosition', Blockly.Arduino.ORDER_ATOMIC);
      var endPosition = parseInt(startPosition) + 1;
      var code = '' + inputText + '[' + startPosition + ':' + endPosition + ']';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //提取字符代码中的文本
    Blockly.Python.extractText = function (block) {
      var inputText = Blockly.Python.valueToCode(this, 'inputText', Blockly.Arduino.ORDER_ATOMIC);
      var code = 'chr(' + inputText + ')';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //convert to text
    Blockly.Python.convertToText = function (block) {
      var integer = Blockly.Python.valueToCode(this, 'integer', Blockly.Arduino.ORDER_ATOMIC);
      var code = "str("+integer + ")";
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //游戏
    //创建精灵
    Blockly.Python.creatingElves = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var x = Blockly.Python.valueToCode(this, 'x', Blockly.Arduino.ORDER_ATOMIC);
      var y = Blockly.Python.valueToCode(this, 'y', Blockly.Arduino.ORDER_ATOMIC);
      sprite = { x: x, y: y, angle: 0, light: 0, LED_time: 100, score: 0, pause: 0 };
      var code = 'display.set_pixel(' + sprite.x + ',' + sprite.y + ',9)';
      return [code, Blockly.Python.ORDER_ATOMIC];
    };
  
    //删除精灵
    Blockly.Python.deleteElves = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var lablex = sprite.x;
      var labley = sprite.y;
      sprite = null;
      var code = 'display.set_pixel(' + lablex + ',' + labley + ',0)\n';
      return [code, Blockly.Python.ORDER_ATOMIC];
    };
  
    //精灵移动
    Blockly.Python.moveSprite = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var move = Blockly.Python.valueToCode(this, 'move', Blockly.Arduino.ORDER_ATOMIC);
      return 'def LED_move(move_vagle):\nglobal location[0], location[1], angle\nmove_two = {45:[ location[0] + move_vagle, location[1] + move_vagle], 135:[ location[0] - move_vagle, location[1] + move_vagle], 225:[ location[0] - move_vagle, location[1] - move_vagle], 315:[ location[1] - move_vagle, location[0] + move_vagle]}}\n'
        + 'if angle == 90:\n  location[1] += move_vagle\nelif angle == 180:\n  location[0] -= move_vagle\nelif angle == 270:\n  location[1] -= move_vagle\nelif angle == 360 or angle == 0:\n  location[0] += move_vagle\nelse:\n  location[0] = move_two[angle][0]\n  location[1] = move_two[angle][1]\n  location[0] = 4 if location[0] > 4 else 0 if location[0] < 0 else location[0]\n  location[1] = 4 if location[1] > 4 else 0 if location[1] < 0 else location[1]\n  display.set_pixel(location[0], location[1], 9)\n'+
        'LED_move('+ move +')\n';
    };
  
    //精灵转向
    Blockly.Python.turnSprite = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var turn = block.getFieldValue('turn');
      var direction = "";
      if (turn == "左转") {
        direction = 1;
      } else {
        direction = 0;
      }
      var angle_move_value = Blockly.Python.valueToCode(this, 'turn', Blockly.Arduino.ORDER_ATOMIC);
      return 'def angle_move(direction,angle_move_value):\n  global angle\n  if direction:\n  for i in range(0, angle_move_value, 45):\n'
        + '    if angle == 0:\n      angle = 360\n    angle -= 45\n  else:\n  for i in range(0, angle_move_value, 45):\n    if angle == 360:\n      angle = 0\n    angle += 45\nangle_move('+ direction +','+ angle_move_value +')';
    };
  
    //精灵更改幅度
    Blockly.Python.updateSpriteAxis = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var axis = block.getFieldValue('axis');
      var code = "";
      if (axis == "x") {
        code = 'display.set_pixel('+sprite.x+', '+sprite.y+', 0)\n'+sprite.x+' = 4 if '+sprite.x+'+1 > 4 else 0 if '+sprite.x+'+1 < 0 else '+sprite.x+'+1\ndisplay.set_pixel('+sprite.x+', '+sprite.y+', 9)';
      } else {
        code = 'display.set_pixel('+sprite.x+' '+sprite.y+', 0)\n'+sprite.y+' = 4 if '+sprite.y+'+1 > 4 else 0 if '+sprite.y+'+1 < 0 else '+sprite.y+'+1\ndisplay.set_pixel('+sprite.x+', '+sprite.y+', 9)';
      }
      return code + '\n';
    };
  
    //精灵Sprite设置轴
    Blockly.Python.setSpriteAxis = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var axis = block.getFieldValue('axis');
      var setValue = Blockly.Python.valueToCode(this, 'set', Blockly.Arduino.ORDER_ATOMIC);
      if (axis == "x") {
        sprite.x= setValue;
      } else {
        sprite.y = setValue;
      }
      return 'display.set_pixel(' + sprite.x + ',' + sprite.y + ',9)\n';
    };
  
    //精灵获取sprite轴
    Blockly.Python.getSpriteAxis = function (block) {
      var axis = block.getFieldValue('axis');
      if (axis == "x") {
        return sprite.x+"";
      } else {
        return sprite.y+"";
      }
    };
  
    //精灵是否遇到
    // Blockly.Python.isMeest = function (block) {
    //   var axis = block.getFieldValue('axis');
    //   var set = Blockly.Python.valueToCode(this, 'set', Blockly.Arduino.ORDER_ATOMIC);
    //   if (axis == "x") {
    //     return sprite[0];
    //   } else {
    //     return sprite[1];
    //   }
    // };
  
    //精灵是否碰到边缘
    Blockly.Python.isTouchEdge = function (block) {
      if (sprite.x == 0 || sprite.x == 4 || sprite.y == 0 || sprite.y == 4) {
        return 'True';
      } else {
        return 'False';
      }
    };
  
    //如果sprite碰到边缘则反弹
    Blockly.Python.touchEdgeEvent = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      return 'if('+sprite.x+' == 0 || '+sprite.x+' == 4 || '+sprite.y+' == 0 || '+sprite.y+' == 4)\n  if angle >= 180:\n    angle -= 180\n  else:\n    angle += 180\n';
    };
  
    //将分数更改
    Blockly.Python.isTouchEdge = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var fraction = Blockly.Python.valueToCode(this, 'fraction', Blockly.Arduino.ORDER_ATOMIC);
      sprite.score += fraction;
      return 'sprite.score += '+ fraction +'\n';
    };
  
    //设置分数
    Blockly.Python.setFractions = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var fraction = Blockly.Python.valueToCode(this, 'fraction', Blockly.Arduino.ORDER_ATOMIC);
      sprite.score = fraction;
      return 'sprite.score = '+ fraction +'\n';
    };
  
    //setLife
    Blockly.Python.setLife = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var lifeNumber = Blockly.Python.valueToCode(this, 'life', Blockly.Arduino.ORDER_ATOMIC);
      sprite.life = lifeNumber;
      return 'sprite.life = '+ lifeNumber +'\n';
    };
  
    //addLife
    Blockly.Python.addLife = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var lifeNumber = Blockly.Python.valueToCode(this, 'life', Blockly.Arduino.ORDER_ATOMIC);
      sprite.life += lifeNumber;
      return 'sprite.life += '+ lifeNumber +'\n';
    };
  
    //removeLife
    Blockly.Python.removeLife = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var lifeNumber = Blockly.Python.valueToCode(this, 'life', Blockly.Arduino.ORDER_ATOMIC);
      sprite.life -= lifeNumber;
      return 'sprite.life -= '+ lifeNumber +'\n';
    };
  
    //getFraction
    Blockly.Python.getFraction = function (block) {
      return sprite.score+"";
    };
  
    //gameOver
    Blockly.Python.gameOver = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      return '  for i in range(8):\n    display.show(Image("99999:99999:99999:99999:99999"))\n    sleep(300)\n    display.show(Image("00000:00000:00000:00000:00000"))\n' +
        '    sleep(300)\n  lift = 0\n  display.scroll("GAME OVER SCORE")\n  display.scroll(str(score))\n';
    };
  
    //isGameOver
    Blockly.Python.isGameOver = function (block) {
      if(sprite.life <= 0){
        return "True\n";
      }else {
        return "False\n";
      }
    };
  
    //isPaused
    Blockly.Python.isPaused = function (block) {
      if(sprite.pause == 1){
        return "True\n";
      }else {
        return "False\n";
      }
    };
  
    //isRunning
    Blockly.Python.isRunning = function (block) {
      if(sprite.score > 0 && sprite.pause == 0){
        return "True\n";
      }else {
        return "False\n";
      }
    };
  
    //paused
    Blockly.Python.paused = function (block) {
      sprite.paused = 1;
      return 'paused\n';
    };
  
    
    //recovery
    Blockly.Python.recovery = function (block) {
      sprite.paused = 0;
      return 'recovery\n';
    };
  
    //图像
    //创建图像
    Blockly.Python.createImage = function (block) {
      var choice = block.getFieldValue('CHOICE');
      if (choice.length <= 0) {
        choice = "0000000000000000000000000";
      }
      var choiceArrray = [];
      for (var i = 0; i < choice.length / 5; i++) {
        choiceArrray.push(choice.substring(i * 5, i * 5 + 5).replace(/1/g, '8'))
      }
      var microbitImage = 'Image("' + choiceArrray[0] + ':' + choiceArrray[1] + ':' + choiceArrray[2] + ':' + choiceArrray[3] + ':' + choiceArrray[4] + '")';
      return [microbitImage, Blockly.Python.ORDER_ATOMIC]
    };
  
    //显示图像
    Blockly.Python.showImage = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var microbitImage = Blockly.Python.valueToCode(this, 'myImage', Blockly.Arduino.ORDER_ATOMIC);
      var position = Blockly.Python.valueToCode(this, 'position', Blockly.Arduino.ORDER_ATOMIC);
      var orientation = block.getFieldValue('orientation');
      console.log(microbitImage);
      var code = "";
      if (orientation == "UP") {
        code = 'display.show(' + microbitImage + '.shift_up(' + position + '))';
      } else if (orientation == "DOWN") {
        code = 'display.show(' + microbitImage + '.shift_down(' + position + '))';
      } else if (orientation == "LEFT") {
        code = 'display.show(' + microbitImage + '.shift_left(' + position + '))';
      } else if (orientation == "RIGHT") {
        code = 'display.show(' + microbitImage + '.shift_right(' + position + '))';
      }
      return code + '\n';
      //return 'display.show('+microbitImage+'.shift_left('+ position +')))';
    };
  
    //滚动图像
    Blockly.Python.rollImage = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var position = Blockly.Python.valueToCode(this, 'position', Blockly.Arduino.ORDER_ATOMIC);
      var time = Blockly.Python.valueToCode(this, 'time', Blockly.Arduino.ORDER_ATOMIC);
      var orientation = block.getFieldValue('orientation');
      var microbitImage = Blockly.Python.valueToCode(this, 'myImage', Blockly.Arduino.ORDER_ATOMIC);
      var code = "";
      if (orientation == "上") {
        code = 'for i in range(0, 5, ' + position + '):\n  display.show(' + microbitImage + '.shift_down(5-i))\n  sleep(' + time + ')\n' +
          'for i in range(0, 5, ' + position + '):\n  display.show(' + microbitImage + '.shift_up(i))\n  sleep(' + time + ')';
      } else if (orientation == "下") {
        code = 'for i in range(0, 5, ' + position + '):\n  display.show(' + microbitImage + '.shift_down(i))\n  sleep(' + time + ')';
      } if (orientation == "左") {
        code = 'for i in range(0, 5, ' + position + '):\n  display.show(' + microbitImage + '.shift_left(i))\n  sleep(' + time + ')\n' +
          'for i in range(0, 5, ' + position + '):\n  display.show(' + microbitImage + '.shift_right(4-i))\n  sleep(' + time + ')';
      } else if (orientation == "右") {
        code = 'for i in range(0, 5, ' + position + '):\n  display.show(' + microbitImage + '.shift_right(5-i))\n  sleep(' + time + ')';
      }
      return code;
      //return 'for i in range(0, 5, 2):\n  display.show(Image("80000:08000:00800:00080:00008").shift_up(5-i))\n  sleep(500)';
    };
  
    //创建图像
    Blockly.Python.arrowImage = function (block) {
      var arrow = block.getFieldValue('arrow');
      var microbitImage;
      if (arrow == 'north') {//北
        microbitImage = 'Image("00100:01110:10101:00100:00100")';
      } else if (arrow == 'south') {//南
        microbitImage = 'Image("00100:00100:10101:01110:00100")';
      } else if (arrow == 'west') {//东
        microbitImage = 'Image("00100:01000:11111:01000:00100")';
      } else if (arrow == 'east') {//西
        microbitImage = 'Image("00100:00010:11111:00010:00100")';
      } else if (arrow == 'southwest') {//西南
        microbitImage = 'Image("00001:00010:10100:11000:11100")';
      } else if (arrow == 'northwest') {//东南
        microbitImage = 'Image("11100:11000:10100:00010:00001")';
      } else if (arrow == 'southeast') {//西北
        microbitImage = 'Image("10000:01000:00101:00011:00111")';
      } else if (arrow == 'northeast') {//东北
        microbitImage = 'Image("00111:00011:00101:01000:10000")';
      }
      microbitImage = microbitImage.replace(/1/g, '8');
      return [microbitImage, Blockly.Python.ORDER_ATOMIC]
    };
    //引脚
    //数字读取引脚
    Blockly.Python.digitalReadPin = function (block) {
      var pin = block.getFieldValue('pin');
      var code = '' + pin + '.read_digital()';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //向引脚数字写入值
    Blockly.Python.writeDigitalValue = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var pin = block.getFieldValue('pin');
      var value = Blockly.Python.valueToCode(this, 'value', Blockly.Arduino.ORDER_ATOMIC);
      return '' + pin + '.write_digital(' + value + ')\n';
    };
  
    //模拟读取引脚
    Blockly.Python.analogReadPin = function (block) {
      var pin = block.getFieldValue('pin');
      var code = '' + pin + '.read_analog()';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //向引脚数字写入模拟值
    Blockly.Python.writeAnalogValue = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var pin = block.getFieldValue('pin');
      var value = Blockly.Python.valueToCode(this, 'value', Blockly.Arduino.ORDER_ATOMIC);
      return '' + pin + '.write_analog(' + value + ')\n';
    };
  
    //设置引脚模拟期间
    Blockly.Python.setSimulationPeriod = function (block) {
      return null;
    };
  
    //映射
    Blockly.Python.mapping = function (block) {
      var a = Blockly.Python.valueToCode(this, 'mapping', Blockly.Arduino.ORDER_ATOMIC);
      var b = Blockly.Python.valueToCode(this, 'low', Blockly.Arduino.ORDER_ATOMIC);
      var c = Blockly.Python.valueToCode(this, 'high', Blockly.Arduino.ORDER_ATOMIC);
      var d = Blockly.Python.valueToCode(this, 'tolow', Blockly.Arduino.ORDER_ATOMIC);
      var e = Blockly.Python.valueToCode(this, 'tohigh', Blockly.Arduino.ORDER_ATOMIC);
      var code = '' + a + ' * ((' + e + ' - ' + d + ') / (' + c + ' - ' + b + '))';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //向伺服机构引脚P0写入angle
    Blockly.Python.writeServoValue = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var pin = block.getFieldValue('pin');
      var value = Blockly.Python.valueToCode(this, 'value', Blockly.Arduino.ORDER_ATOMIC);
      return pin + '.write_analog((0.5 + ' + value + '/90)*1023/15)\n';
    };
  
    //将伺服机构 引脚P0 脉冲设置
    Blockly.Python.setServoPulse = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var pin = block.getFieldValue('pin');
      var value = Blockly.Python.valueToCode(this, 'pulse', Blockly.Arduino.ORDER_ATOMIC);
      return  pin + '.set_analog_period(' + value + ')\n';
    };
  
    //当引脚状态改变时
    Blockly.Python.statusChangesEvent = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var pin = block.getFieldValue('pin');
      var status = block.getFieldValue('status');
      var cod = '';
      if (status == 'high') {
        cod = 'if ' + pin + '.read_digital:'
      } else if (status == 'low') {
        cod = 'if not ' + pin + '.read_digital:'
      }
      var branch = Blockly.Python.statementToCode(this, 'DO')  || Blockly.Python.PASS;
      var code2 = `${cod} \n ${branch}\n`;
      return code2;
    };
  
  
    //脉冲引脚持续时间（μs）——
    Blockly.Python.pulseDurationPin = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_utime'] = 'import utime';
      var pin = block.getFieldValue('pin');
      var status = block.getFieldValue('status');
      var code ='';
      var highCode = 'def durationHighTime(pin):\n'+
        '    time = 0\n'+
        '    if pin.read_digital():\n'+
        '        time_start = utime.ticks_ms()\n'+
        '        while pin.read_digital():\n'+
        '            pass\n'+
        '        time = utime.ticks_ms() - time_start\n'+
        '    return time\n';
      var lowCode = 'def durationLowTime(pin):\n'+
      '    time = 0\n'+
      '    if not pin.read_digital():\n'+
      '        time_start = utime.ticks_ms()\n'+
      '        while not pin.read_digital():\n'+
      '            pass\n'+
      '        time = utime.ticks_ms() - time_start\n'+
      '    return time\n';
      Blockly.Python.definitions_['import_defHighTime'] = highCode;
      Blockly.Python.definitions_['import_defLowTime'] = lowCode;
      if (status == "high") {
        code = 'durationHighTime('+ pin + ')';
      } else if (status == "low") {
        code = 'durationLowTime('+ pin + ')';
      }
      return  [code, Blockly.Python.ORDER_ATOMIC];
    };
  
    //i2cReadNumber
    Blockly.Python.i2cReadNumber = function (block) {
      return 'null';
    };
  
    //i2cWriteNumber
    Blockly.Python.i2cWriteNumber = function (block) {
      return 'null';
    };
  
    //spi写入 4
    Blockly.Python.spiWrite = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var value = Blockly.Python.valueToCode(this, 'value', Blockly.Arduino.ORDER_ATOMIC);
      var code = 'spi.write(bytes(' + value + '))';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //模拟音阶
    Blockly.Python.analogueScale = function (block) {
      return 'null';
    };
  
    //设置引脚 P0 以激发 边缘 事件   
    Blockly.Python.setPinEvents = function (block) {
      return 'null';
    };
  
    //spi频率 1000000
    Blockly.Python.spiFrequency = function (block) {
      var value = Blockly.Python.valueToCode(this, 'value', Blockly.Arduino.ORDER_ATOMIC);
      return 'spi.init(baudrate=' + value + ')\n';
    };
  
    //设置模拟音阶引脚
    Blockly.Python.setAnalogScalePin = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitmusic'] = 'import music';
      var pin = block.getFieldValue('pin');
      var frequency = Blockly.Python.valueToCode(this, 'frequency', Blockly.Arduino.ORDER_ATOMIC);
      var time = Blockly.Python.valueToCode(this, 'time', Blockly.Arduino.ORDER_ATOMIC);
      return 'music.pitch(' + frequency + ', ' + time + ', pin=' + pin + ', wait=True)\n';
    };
  
    //设置拉 引脚music。
    Blockly.Python.setPullPin = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      return 'null';
    };
  
    //spi 格式 位数
    Blockly.Python.spiFormatDigits = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var value = block.getFieldValue('value');
      var mode = block.getFieldValue('mode');
      // var value = Blockly.Python.valueToCode(this, 'value', Blockly.Arduino.ORDER_ATOMIC);
      // var mode = Blockly.Python.valueToCode(this, 'mode', Blockly.Arduino.ORDER_ATOMIC);
      return 'spi.init(bits=' + value + ', mode=' + mode + ')  \n';
    };
  
    //spi 设置引脚
    Blockly.Python.spiSetPin = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var mosi = block.getFieldValue('mosi');
      var miso = block.getFieldValue('miso');
      var sdk = block.getFieldValue('sdk');
      return 'spi.init(sclk=' + sdk + ', mosi=' + mosi + ', miso=' + miso + ')\n';
    };
  
    //串行
    //串口打印microbit
    Blockly.Python.serialPrintingString = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var value = Blockly.Python.valueToCode(this, 'value', Blockly.Arduino.ORDER_ATOMIC);
      value = value.replace(/'/g,"");
      return 'print(' + value + ')\n';
    };
  
    //向串口写入一行
    Blockly.Python.writeLineToSerial = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var value = Blockly.Python.valueToCode(this, 'value', Blockly.Arduino.ORDER_ATOMIC);
      value = value.replace(/'/g,"");
      return 'uart.write(bytearray(' + value + '+"\\n"))\n';
    };
  
    //串口写入数字
    Blockly.Python.writeNumberToSerial = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var value = Blockly.Python.valueToCode(this, 'value', Blockly.Arduino.ORDER_ATOMIC);
      var value = "\"" + value + "\"";
      return 'uart.write(bytearray(' + value + '+"\\n"))\n';
    };
  
    //串口写入数值
    Blockly.Python.writeValueToSerial = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var name = Blockly.Python.valueToCode(this, 'name', Blockly.Arduino.ORDER_ATOMIC);
      var value = Blockly.Python.valueToCode(this, 'value', Blockly.Arduino.ORDER_ATOMIC);
      return 'uart.write((bytearray(' + value + '+' + name + '+"\\n"))\n';
    };
  
    //串口写入字符串
    Blockly.Python.writeStringToSerial = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var value = Blockly.Python.valueToCode(this, 'value', Blockly.Arduino.ORDER_ATOMIC);
      return 'uart.write((bytearray(' + value + ')))\n';
    };
  
    // //串口写入字符串
    // Blockly.Python.writeStringToSerial = function (block) {
    //   var value = Blockly.Python.valueToCode(this, 'value', Blockly.Arduino.ORDER_ATOMIC);
    //   return 'uart.write((bytearray(' + value + '))\n';
    // };
  
    //从串口读取行
    Blockly.Python.readLineToSerial = function (block) {
      var code = 'uart.readline()';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //从串口读取，直至遇到 换行
    Blockly.Python.readSerialData = function (block) {
      var value = Blockly.Python.valueToCode(this, 'value', Blockly.Arduino.ORDER_ATOMIC);
      var code = 'index = 0\nvalue = ' + value + '\nwhile True:\nif uart.any():\none_byte = uart.read(1)\n'
        + 'if ord(one_byte)!=36:\nvalue[index] = one_byte\nindex += 1\nelse:\nbreak';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //串口读取字符串
    Blockly.Python.readSerialString = function (block) {
      var code = 'uart.read()';
      return [code, Blockly.Python.ORDER_ATOMIC]
    };
  
    //串口写入字符串
    Blockly.Python.serialStatusChangesEvent = function (block) {
      return 'null';
    };
  
    //串行 重定向
    Blockly.Python.serialRedirection = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      var pinTX = block.getFieldValue('pinTX');
      var pinRX = block.getFieldValue('pinRX');
      var baudRate = block.getFieldValue('baudRate');
      return 'uart.init(baudrate=' + baudRate + ', bits=8, parity=None, stop=1, tx=' + pinTX + ', rx=' + pinRX + ') \n';
    };
  
    //串行 重定向到USB
    Blockly.Python.serialRedirectionUSB = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      return 'uart.init(115200)\n';
    };
  
  
    //控制
    //重置
    Blockly.Python.reset = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      return 'reset()\n';
    };
  
    //等待（μs）
    Blockly.Python.waiting = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbit_utime'] = 'import utime';
      var value = Blockly.Python.valueToCode(this, 'value', Blockly.Arduino.ORDER_ATOMIC);
      return 'utime.sleep_us(' + value + ')\n';
    };
  
  
    Blockly.Python['controls_if'] = function (block) {
      var n = 0;
      var code = '', branchCode, conditionCode;
      do {
        conditionCode = Blockly.Python.valueToCode(block, 'CONDITION' + n,
          Blockly.Python.ORDER_NONE) || 'False';
        branchCode = Blockly.Python.statementToCode(block, 'SUBSTACK' + n) ||
          Blockly.Python.PASS;
        code += (n > 0 ? 'else ' : '') +
          'if ' + conditionCode + ' :\n' + branchCode + '';
        ++n;
      } while (block.getInput('IF' + n));
  
      if (block.getInput('SUBSTACK2')) {
        branchCode = Blockly.Python.statementToCode(block, 'SUBSTACK2') ||
          Blockly.Python.PASS;
        code += 'else :\n' + branchCode + '';
      }
      return code + '\n';
    };
  
    Blockly.Python.control_if_else = Blockly.Python.controls_if;
  
    // 控制：while循环
    Blockly.Python._while = function (block) {
      var value__whiles = Blockly.Python.valueToCode(this, '_whiles', Blockly.Python.ORDER_ATOMIC);
      if (value__whiles.includes('true')) value__whiles = 'True';
      const branch = Blockly.Python.statementToCode(this, 'DO') || Blockly.Python.PASS;;
      const code2 = `while ${value__whiles.replace(/'/g, '')}: \n${branch}\n`;
      return code2;
    };
  
    // 显示屏显赫字符串
    Blockly.Python['displayShow'] = function (block) {
      var value = Blockly.Python.valueToCode(this, 'value', Blockly.Python.ORDER_ATOMIC);
      return 'display.scroll(' + value + ')\n';
    }
  
    Blockly.Python['displayShowClear'] = function (block) {
      // var value = Blockly.Python.valueToCode(this, 'value', Blockly.Python.ORDER_ATOMIC);
      return 'display.clear( )\n';
    }
  
  
    // dowhile
    Blockly.Python.dowhile = function () {
      let value_dowhiles = Blockly.Python.valueToCode(this, 'dowhiles', Blockly.Python.ORDER_ATOMIC);
      if (value_dowhiles === true) value_dowhiles = True;
      let branch = Blockly.Python.statementToCode(this, 'DO');
      let code = `do :\n${branch}while ${value_dowhiles.replace(/'/g, '')}\n`;
      return code;
    };
  
    Blockly.Python['control_wait'] = function (block) {
      var repeats = Blockly.Python.valueToCode(block, 'DURATION',
        Blockly.Python.ORDER_ASSIGNMENT) || '0';
      return 'sleep(' + repeats + ')\n';
    };
  
    Blockly.Python['data_variable'] = function (block) {
      // Variable getter.
      var code = Blockly.Python.variableDB_.getName(block.getFieldValue('VARIABLE'),
        Blockly.Variables.NAME_TYPE);
      return [code, Blockly.Python.ORDER_ATOMIC];
    };
  
    Blockly.Python['data_setvariableto'] = function (block) {
      // Variable setter.
      var argument0 = Blockly.Python.valueToCode(block, 'VALUE',
        Blockly.JavaScript.ORDER_ASSIGNMENT) || '0';
      var varName = Blockly.Python.variableDB_.getName(
        block.getFieldValue('VARIABLE'), Blockly.Variables.NAME_TYPE);
      return varName + ' = ' + argument0 + ';\n';
    };
  
    Blockly.Python['text'] = function (block) {
      // Text value.
      var code = Blockly.Python.quote_(block.getFieldValue('TEXT'));
      return [code, Blockly.Python.ORDER_ATOMIC];
    };
  
    /**
     * Enclose the provided value in 'String(...)' function.
     * Leave string literals alone.
     * @param {string} value Code evaluating to a value.
     * @return {string} Code evaluating to a string.
     * @private
     */
    Blockly.Python.text.forceString_ = function (value) {
      if (Blockly.Python.text.forceString_.strRegExp.test(value)) {
        return value;
      }
      return 'String(' + value + ')';
    };
  
    /**
     * Regular expression to detect a single-quoted string literal.
     */
    Blockly.Python.text.forceString_.strRegExp = /^\s*'([^']|\\')*'\s*$/;
  
    Blockly.Python['text_join'] = function (block) {
      // Create a string made up of any number of elements of any type.
      switch (block.itemCount_) {
        case 0:
          return ['\'\'', Blockly.Python.ORDER_ATOMIC];
        case 1:
          var element = Blockly.Python.valueToCode(block, 'ADD0',
            Blockly.Python.ORDER_NONE) || '\'\'';
          var code = Blockly.Python.text.forceString_(element);
          return [code, Blockly.Python.ORDER_FUNCTION_CALL];
        case 2:
          var element0 = Blockly.Python.valueToCode(block, 'ADD0',
            Blockly.Python.ORDER_NONE) || '\'\'';
          var element1 = Blockly.Python.valueToCode(block, 'ADD1',
            Blockly.Python.ORDER_NONE) || '\'\'';
          var code = Blockly.Python.text.forceString_(element0) + ' + ' +
            Blockly.Python.text.forceString_(element1);
          return [code, Blockly.Python.ORDER_ADDITION];
        default:
          var elements = new Array(block.itemCount_);
          for (var i = 0; i < block.itemCount_; i++) {
            elements[i] = Blockly.Python.valueToCode(block, 'ADD' + i,
              Blockly.Python.ORDER_COMMA) || '\'\'';
          }
          var code = '[' + elements.join(',') + '].join(\'\')';
          return [code, Blockly.Python.ORDER_FUNCTION_CALL];
      }
    };
  
    Blockly.Python.control_repeat = function (block) {
  
  
      // Repeat n times.
      if (block.getField('TIMES')) {
        // Internal number.
        var repeats = String(parseInt(block.getFieldValue('TIMES'), 10));
      } else {
        // External number.
        var repeats = Blockly.Python.valueToCode(block, 'TIMES',
          Blockly.Python.ORDER_NONE) || '0';
      }
      if (Blockly.isNumber(repeats)) {
        repeats = parseInt(repeats, 10);
      } else {
        repeats = 'int(' + repeats + ')';
      }
      var branch = Blockly.Python.statementToCode(block, 'SUBSTACK');
      branch = Blockly.Python.addLoopTrap(branch, block.id) ||
        Blockly.Python.PASS;
      var loopVar = Blockly.Python.variableDB_.getDistinctName(
        'count', Blockly.Variables.NAME_TYPE);
      var code = 'for ' + loopVar + ' in range(' + repeats + '):\n' + branch;
      return code;
    };
  
    Blockly.Python['controls_repeat'] = Blockly.Python['control_repeat'];
  
    Blockly.Python.control_forever = function (block) {
      // Do while/until loop.
      const until = block.getFieldValue('MODE') == 'UNTIL';
      let argument0 = Blockly.Python.valueToCode(block, 'BOOL',
        until ? Blockly.Arduino.ORDER_LOGICAL_NOT :
          Blockly.Python.ORDER_NONE) || 'True';
      let branch = Blockly.Python.statementToCode(block, 'SUBSTACK');
      branch = Blockly.Python.addLoopTrap(branch, block.id) ||
        Blockly.Python.PASS;
      if (until) {
        argument0 = `!${argument0}`;
      }
      return `while ${argument0}: \n${branch}\n`;
    };
  
    Blockly.Python['text_append'] = function (block) {
      // Append to a variable in place.
      var varName = Blockly.Python.variableDB_.getName(
        block.getFieldValue('VAR'), Blockly.Variables.NAME_TYPE);
      var value = Blockly.Python.valueToCode(block, 'TEXT',
        Blockly.Python.ORDER_NONE) || '\'\'';
      return varName + ' += ' + Blockly.Python.text.forceString_(value) + ';\n';
    };
  
    Blockly.Python['text_length'] = function (block) {
      // String or array length.
      var text = Blockly.Python.valueToCode(block, 'VALUE',
        Blockly.Python.ORDER_FUNCTION_CALL) || '\'\'';
      return [text + '.length', Blockly.Python.ORDER_MEMBER];
    };
  
    Blockly.Python['text_isEmpty'] = function (block) {
      // Is the string null or array empty?
      var text = Blockly.Python.valueToCode(block, 'VALUE',
        Blockly.Python.ORDER_MEMBER) || '\'\'';
      return ['!' + text + '.length', Blockly.Python.ORDER_LOGICAL_NOT];
    };
  
    Blockly.Python['text_indexOf'] = function (block) {
      // Search the text for a substring.
      var operator = block.getFieldValue('END') == 'FIRST' ?
        'indexOf' : 'lastIndexOf';
      var substring = Blockly.Python.valueToCode(block, 'FIND',
        Blockly.Python.ORDER_NONE) || '\'\'';
      var text = Blockly.Python.valueToCode(block, 'VALUE',
        Blockly.Python.ORDER_MEMBER) || '\'\'';
      var code = text + '.' + operator + '(' + substring + ')';
      // Adjust index if using one-based indices.
      if (block.workspace.options.oneBasedIndex) {
        return [code + ' + 1', Blockly.Python.ORDER_ADDITION];
      }
      return [code, Blockly.Python.ORDER_FUNCTION_CALL];
    };
  
    Blockly.Python['text_charAt'] = function (block) {
      // Get letter at index.
      // Note: Until January 2013 this block did not have the WHERE input.
      var where = block.getFieldValue('WHERE') || 'FROM_START';
      var textOrder = (where == 'RANDOM') ? Blockly.Python.ORDER_NONE :
        Blockly.Python.ORDER_MEMBER;
      var text = Blockly.Python.valueToCode(block, 'VALUE',
        textOrder) || '\'\'';
      switch (where) {
        case 'FIRST':
          var code = text + '.charAt(0)';
          return [code, Blockly.Python.ORDER_FUNCTION_CALL];
        case 'LAST':
          var code = text + '.slice(-1)';
          return [code, Blockly.Python.ORDER_FUNCTION_CALL];
        case 'FROM_START':
          var at = Blockly.Python.getAdjusted(block, 'AT');
          // Adjust index if using one-based indices.
          var code = text + '.charAt(' + at + ')';
          return [code, Blockly.Python.ORDER_FUNCTION_CALL];
        case 'FROM_END':
          var at = Blockly.Python.getAdjusted(block, 'AT', 1, true);
          var code = text + '.slice(' + at + ').charAt(0)';
          return [code, Blockly.Python.ORDER_FUNCTION_CALL];
        case 'RANDOM':
          var functionName = Blockly.Python.provideFunction_(
            'textRandomLetter',
            ['function ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ +
              '(text) {',
              '  var x = Math.floor(Math.random() * text.length);',
              '  return text[x];',
              '}']);
          var code = functionName + '(' + text + ')';
          return [code, Blockly.Python.ORDER_FUNCTION_CALL];
      }
      throw Error('Unhandled option (text_charAt).');
    };
  
    /**
     * Returns an expression calculating the index into a string.
     * @param {string} stringName Name of the string, used to calculate length.
     * @param {string} where The method of indexing, selected by dropdown in Blockly
     * @param {string=} opt_at The optional offset when indexing from start/end.
     * @return {string} Index expression.
     * @private
     */
    Blockly.Python.text.getIndex_ = function (stringName, where, opt_at) {
      if (where == 'FIRST') {
        return '0';
      } else if (where == 'FROM_END') {
        return stringName + '.length - 1 - ' + opt_at;
      } else if (where == 'LAST') {
        return stringName + '.length - 1';
      } else {
        return opt_at;
      }
    };
  
    Blockly.Python['text_getSubstring'] = function (block) {
      // Get substring.
      var text = Blockly.Python.valueToCode(block, 'STRING',
        Blockly.Python.ORDER_FUNCTION_CALL) || '\'\'';
      var where1 = block.getFieldValue('WHERE1');
      var where2 = block.getFieldValue('WHERE2');
      if (where1 == 'FIRST' && where2 == 'LAST') {
        var code = text;
      } else if (text.match(/^'?\w+'?$/) ||
        (where1 != 'FROM_END' && where1 != 'LAST' &&
          where2 != 'FROM_END' && where2 != 'LAST')) {
        // If the text is a variable or literal or doesn't require a call for
        // length, don't generate a helper function.
        switch (where1) {
          case 'FROM_START':
            var at1 = Blockly.Python.getAdjusted(block, 'AT1');
            break;
          case 'FROM_END':
            var at1 = Blockly.Python.getAdjusted(block, 'AT1', 1, false,
              Blockly.Python.ORDER_SUBTRACTION);
            at1 = text + '.length - ' + at1;
            break;
          case 'FIRST':
            var at1 = '0';
            break;
          default:
            throw Error('Unhandled option (text_getSubstring).');
        }
        switch (where2) {
          case 'FROM_START':
            var at2 = Blockly.Python.getAdjusted(block, 'AT2', 1);
            break;
          case 'FROM_END':
            var at2 = Blockly.Python.getAdjusted(block, 'AT2', 0, false,
              Blockly.Python.ORDER_SUBTRACTION);
            at2 = text + '.length - ' + at2;
            break;
          case 'LAST':
            var at2 = text + '.length';
            break;
          default:
            throw Error('Unhandled option (text_getSubstring).');
        }
        code = text + '.slice(' + at1 + ', ' + at2 + ')';
      } else {
        var at1 = Blockly.Python.getAdjusted(block, 'AT1');
        var at2 = Blockly.Python.getAdjusted(block, 'AT2');
        var getIndex_ = Blockly.Python.text.getIndex_;
        var wherePascalCase = {
          'FIRST': 'First', 'LAST': 'Last',
          'FROM_START': 'FromStart', 'FROM_END': 'FromEnd'
        };
        var functionName = Blockly.Python.provideFunction_(
          'subsequence' + wherePascalCase[where1] + wherePascalCase[where2],
          ['function ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ +
            '(sequence' +
            // The value for 'FROM_END' and'FROM_START' depends on `at` so
            // we add it as a parameter.
            ((where1 == 'FROM_END' || where1 == 'FROM_START') ? ', at1' : '') +
            ((where2 == 'FROM_END' || where2 == 'FROM_START') ? ', at2' : '') +
            ') {',
          '  var start = ' + getIndex_('sequence', where1, 'at1') + ';',
          '  var end = ' + getIndex_('sequence', where2, 'at2') + ' + 1;',
            '  return sequence.slice(start, end);',
            '}']);
        var code = functionName + '(' + text +
          // The value for 'FROM_END' and 'FROM_START' depends on `at` so we
          // pass it.
          ((where1 == 'FROM_END' || where1 == 'FROM_START') ? ', ' + at1 : '') +
          ((where2 == 'FROM_END' || where2 == 'FROM_START') ? ', ' + at2 : '') +
          ')';
      }
      return [code, Blockly.Python.ORDER_FUNCTION_CALL];
    };
  
    Blockly.Python['text_changeCase'] = function (block) {
      // Change capitalization.
      var OPERATORS = {
        'UPPERCASE': '.toUpperCase()',
        'LOWERCASE': '.toLowerCase()',
        'TITLECASE': null
      };
      var operator = OPERATORS[block.getFieldValue('CASE')];
      var textOrder = operator ? Blockly.Python.ORDER_MEMBER :
        Blockly.Python.ORDER_NONE;
      var text = Blockly.Python.valueToCode(block, 'TEXT',
        textOrder) || '\'\'';
      if (operator) {
        // Upper and lower case are functions built into JavaScript.
        var code = text + operator;
      } else {
        // Title case is not a native JavaScript function.  Define one.
        var functionName = Blockly.Python.provideFunction_(
          'textToTitleCase',
          ['function ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ +
            '(str) {',
            '  return str.replace(/\\S+/g,',
          '      function(txt) {return txt[0].toUpperCase() + ' +
          'txt.substring(1).toLowerCase();});',
            '}']);
        var code = functionName + '(' + text + ')';
      }
      return [code, Blockly.Python.ORDER_FUNCTION_CALL];
    };
  
    Blockly.Python['text_trim'] = function (block) {
      // Trim spaces.
      var OPERATORS = {
        'LEFT': ".replace(/^[\\s\\xa0]+/, '')",
        'RIGHT': ".replace(/[\\s\\xa0]+$/, '')",
        'BOTH': '.trim()'
      };
      var operator = OPERATORS[block.getFieldValue('MODE')];
      var text = Blockly.Python.valueToCode(block, 'TEXT',
        Blockly.Python.ORDER_MEMBER) || '\'\'';
      return [text + operator, Blockly.Python.ORDER_FUNCTION_CALL];
    };
  
    Blockly.Python['text_print'] = function (block) {
      // Print statement.
      var msg = Blockly.Python.valueToCode(block, 'TEXT',
        Blockly.Python.ORDER_NONE) || '\'\'';
      return 'window.alert(' + msg + ');\n';
    };
  
    Blockly.Python['text_prompt_ext'] = function (block) {
      // Prompt function.
      if (block.getField('TEXT')) {
        // Internal message.
        var msg = Blockly.Python.quote_(block.getFieldValue('TEXT'));
      } else {
        // External message.
        var msg = Blockly.Python.valueToCode(block, 'TEXT',
          Blockly.Python.ORDER_NONE) || '\'\'';
      }
      var code = 'window.prompt(' + msg + ')';
      var toNumber = block.getFieldValue('TYPE') == 'NUMBER';
      if (toNumber) {
        code = 'parseFloat(' + code + ')';
      }
      return [code, Blockly.Python.ORDER_FUNCTION_CALL];
    };
  
    Blockly.Python['text_prompt'] = Blockly.Python['text_prompt_ext'];
  
    Blockly.Python['text_count'] = function (block) {
      var text = Blockly.Python.valueToCode(block, 'TEXT',
        Blockly.Python.ORDER_MEMBER) || '\'\'';
      var sub = Blockly.Python.valueToCode(block, 'SUB',
        Blockly.Python.ORDER_NONE) || '\'\'';
      var functionName = Blockly.Python.provideFunction_(
        'textCount',
        ['function ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ +
          '(haystack, needle) {',
          '  if (needle.length === 0) {',
          '    return haystack.length + 1;',
          '  } else {',
          '    return haystack.split(needle).length - 1;',
          '  }',
          '}']);
      var code = functionName + '(' + text + ', ' + sub + ')';
      return [code, Blockly.Python.ORDER_SUBTRACTION];
    };
  
    Blockly.Python['text_replace'] = function (block) {
      var text = Blockly.Python.valueToCode(block, 'TEXT',
        Blockly.Python.ORDER_MEMBER) || '\'\'';
      var from = Blockly.Python.valueToCode(block, 'FROM',
        Blockly.Python.ORDER_NONE) || '\'\'';
      var to = Blockly.Python.valueToCode(block, 'TO',
        Blockly.Python.ORDER_NONE) || '\'\'';
      // The regex escaping code below is taken from the implementation of
      // goog.string.regExpEscape.
      var functionName = Blockly.Python.provideFunction_(
        'textReplace',
        ['function ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ +
          '(haystack, needle, replacement) {',
        '  needle = ' +
        'needle.replace(/([-()\\[\\]{}+?*.$\\^|,:#<!\\\\])/g,"\\\\$1")',
          '                 .replace(/\\x08/g,"\\\\x08");',
          '  return haystack.replace(new RegExp(needle, \'g\'), replacement);',
          '}']);
      var code = functionName + '(' + text + ', ' + from + ', ' + to + ')';
      return [code, Blockly.Python.ORDER_MEMBER];
    };
  
    Blockly.Python['text_reverse'] = function (block) {
      var text = Blockly.Python.valueToCode(block, 'TEXT',
        Blockly.Python.ORDER_MEMBER) || '\'\'';
      var code = text + '.split(\'\').reverse().join(\'\')';
      return [code, Blockly.Python.ORDER_MEMBER];
    };
  
    Blockly.Python['operator_equals'] = function (block) {
      var order = Blockly.Python.ORDER_EQUALITY;
      var argument0 = Blockly.Python.valueToCode(block, 'OPERAND1', order) || '0';
      var argument1 = Blockly.Python.valueToCode(block, 'OPERAND2', order) || '0';
      var code = "str("+ argument0.replace(/'/g, "") +')'+ '==' + 'str(' + argument1.replace(/'/g, "") + ')';
      return [code, order];
    };
  
    Blockly.Python['operator_lt'] = function (block) {
      var order = Blockly.Python.ORDER_EQUALITY;
      var argument0 = Blockly.Python.valueToCode(block, 'OPERAND1', order) || '0';
      var argument1 = Blockly.Python.valueToCode(block, 'OPERAND2', order) || '0';
      var code = argument0.replace(/'/g, "") + ' ' + '<' + ' ' + argument1.replace(/'/g, "");
      return [code, order];
    };
  
    Blockly.Python['operator_gt'] = function (block) {
      var order = Blockly.Python.ORDER_EQUALITY;
      var argument0 = Blockly.Python.valueToCode(block, 'OPERAND1', order) || '0';
      var argument1 = Blockly.Python.valueToCode(block, 'OPERAND2', order) || '0';
      var code = argument0.replace(/'/g, "") + ' ' + '>' + ' ' + argument1.replace(/'/g, "");
      return [code, order];
    };
  
    Blockly.Python['creater_variable'] = function (block) {
      var order = Blockly.Python.ORDER_EQUALITY;
      var type = this.getFieldValue('BACKDROP');
      var variable = Blockly.Python.valueToCode(block, 'OPERAND1', order) || '0';
      variable = variable.replace(/'/g, '');
      var code = type + '  ' + variable + ';\n';
      return code;
    };
  
    Blockly.Python['set_variable'] = function (block) {
      var order = Blockly.Python.ORDER_EQUALITY;
      var argument0 = Blockly.Python.valueToCode(block, 'STEPS', order) || '0';
      var argument1 = Blockly.Python.valueToCode(block, 'STEPS1', order) || '0';
      var code = argument0.replace(/'/g, "") + ' ' + '=' + ' ' + argument1.replace(/'/g, "") + '\n';
      return code;
    };
  
    Blockly.Python['get_variable'] = function (block) {
      var order = Blockly.Python.ORDER_EQUALITY;
      var argument0 = Blockly.Python.valueToCode(block, 'STEPS1', order) || '0';
      var code = argument0.replace(/'/g, "");
      return [code];
    };
  
    Blockly.Python.operator_add = function (block) {
      // +
      const order = Blockly.Python.ORDER_ASSIGNMENT;
      const argument1 = Blockly.Python.valueToCode(block, 'NUM1', order) || 0;
      const argument2 = Blockly.Python.valueToCode(block, 'NUM2', order) || 0;
      const code = `${argument1} + ${argument2}`;
      return [code.replace(/\'/g, ''), order];
    };
  
    Blockly.Python.operator_subtract = function (block) {
      // -
      const order = Blockly.Python.ORDER_ASSIGNMENT;
      const argument1 = Blockly.Python.valueToCode(block, 'NUM1', order) || 0;
      const argument2 = Blockly.Python.valueToCode(block, 'NUM2', order) || 0;
      const code = `${argument1} - ${argument2}`;
      return [code.replace(/\'/g, ''), order];
    };
  
    Blockly.Python.operator_multiply = function (block) {
      // *
      const order = Blockly.Python.ORDER_ASSIGNMENT;
      const argument1 = Blockly.Python.valueToCode(block, 'NUM1', order) || 0;
      const argument2 = Blockly.Python.valueToCode(block, 'NUM2', order) || 0;
      const code = `${argument1} * ${argument2}`;
      return [code.replace(/\'/g, ''), order];
    };
  
    Blockly.Python.operator_divide = function (block) {
      // /
      const order = Blockly.Python.ORDER_ASSIGNMENT;
      const argument1 = Blockly.Python.valueToCode(block, 'NUM1', order) || 0;
      const argument2 = Blockly.Python.valueToCode(block, 'NUM2', order) || 0;
      const code = `${argument1} / ${argument2}`;
      return [code.replace(/\'/g, ''), order];
    };
  
    Blockly.Python.operator_notbools = function (block) {
      const order = Blockly.Python.ORDER_ASSIGNMENT;
      const variable = Blockly.Python.valueToCode(block, 'OPERAND1', order) || '0';
      const code = "not ' '";
      return [code];
    };
  
    Blockly.Python.notis = function () {
      let value_notiss1 = Blockly.Python.valueToCode(this, 'notiss1', Blockly.Python.ORDER_ATOMIC);
      let value_notiss2 = Blockly.Python.valueToCode(this, 'notiss2', Blockly.Python.ORDER_ATOMIC);
      let code = `${value_notiss1.replace(/'/g, '')}!=${value_notiss2.replace(/'/g, '')}`;
      return [code, Blockly.Python.ORDER_ATOMIC];
    };
  
    Blockly.Python.operator_ands = function (block) {
      const order = Blockly.Python.ORDER_ASSIGNMENT;
      const argument1 = Blockly.Python.valueToCode(block, 'OPERAND1', order) || 0;
      const argument2 = Blockly.Python.valueToCode(block, 'OPERAND2', order) || 0;
      const code = `${argument1} and ${argument2}`;
      return [code, order];
    };
  
    Blockly.Python.operator_ors = function (block) {
      // Numeric value.
      const order = Blockly.Python.ORDER_ASSIGNMENT;
      const argument1 = Blockly.Python.valueToCode(block, 'OPERAND1', order) || 0;
      const argument2 = Blockly.Python.valueToCode(block, 'OPERAND2', order) || 0;
      const code = `${argument1} or ${argument2}`;
      return [code, order];
    };
  
    Blockly.Python.operator_bools = function (block) {
      const argument1 = this.getFieldValue('BACKDROP');
      if (argument1 === 'true') return ['True'];
      return ['False'];
    };
  
    Blockly.Python.operator_not = function (block) {
      // Numeric value.
      const order = Blockly.Python.ORDER_ASSIGNMENT;
      const argument1 = Blockly.Python.valueToCode(block, 'OPERAND1', order) || 0;
      const argument2 = Blockly.Python.valueToCode(block, 'OPERAND2', order) || 0;
      const code = `${argument1} not ${argument2}`;
      return [code, order];
    };
  
    Blockly.Arduino.operator_notbools = function (block) {
      const order = Blockly.Arduino.ORDER_ASSIGNMENT;
      const variable = Blockly.Arduino.valueToCode(block, 'OPERAND1', order) || '0';
      const code = `!${variable}`;
      return [code];
    };
  
    Blockly.Python['math_number'] = function (block) {
      // Numeric value.
      var code = parseFloat(block.getFieldValue('NUM'));
      var order = code >= 0 ? Blockly.Python.ORDER_ATOMIC :
        Blockly.Python.ORDER_UNARY_NEGATION;
      return [code, order];
    };
  
    Blockly.Python['math_whole_number'] = function (block) {
      // Numeric value.
      var code = parseFloat(block.getFieldValue('NUM'));
      var order = code >= 0 ? Blockly.Python.ORDER_ATOMIC :
        Blockly.Python.ORDER_UNARY_NEGATION;
      return [code, order];
    };
  
    Blockly.Python.math_number = function (block) {
      // Numeric value.
      const code = parseFloat(block.getFieldValue('NUM'));
      const order = code >= 0 ? Blockly.Arduino.ORDER_ATOMIC :
        Blockly.Arduino.ORDER_UNARY_NEGATION;
      return [code, order];
    };
  
    Blockly.Python.math_whole_number = function (block) {
      // Numeric value.
      const code = parseFloat(block.getFieldValue('NUM'));
      const order = code >= 0 ? Blockly.Arduino.ORDER_ATOMIC :
        Blockly.Arduino.ORDER_UNARY_NEGATION;
      return [code, order];
    };




    Blockly.Python.initPCA9685 = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import display';
      Blockly.Python.definitions_['import_microbithello'] = 'from hello import say_hello';
      // Blockly.Python.definitions_['import_microbitMagicbit'] = 'import magicbit';
      code = "display.scroll(say_hello())";
      // code = code+"  print(hello.read())";
      // var code = "with open('C:/Users/asus/Desktop/hello.py', 'r') as hello\n";
  
       return code;
    }
  
    //舵机角度
    Blockly.Python.servoSpeed = function (block) {
      var servo = block.getFieldValue('servo');
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitMotor'] = 'import motor';
      Blockly.Python.definitions_['import_microbitMotorInit'] = 'motorbit = motor.init()';
      var servoDegree  = Blockly.Python.valueToCode(this, 'servoDegree', Blockly.Arduino.ORDER_ATOMIC);
      return 'motorbit.servo(' + servo + ', ' + servoDegree  +')\n';
    };
  
      //舵机起始角度和转速
    Blockly.Python.steeringAngle = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitMotor'] = 'import motor';
      Blockly.Python.definitions_['import_microbitMotorInit'] = 'motorbit = motor.init()';
      var Steering =  block.getFieldValue('Steering');
      var degree = Blockly.Python.valueToCode(this, 'degree', Blockly.Arduino.ORDER_ATOMIC); 
      var endDegree = Blockly.Python.valueToCode(this, 'endDegree', Blockly.Arduino.ORDER_ATOMIC); 
      var steeringVelocity = Blockly.Python.valueToCode(this, 'steeringVelocity', Blockly.Arduino.ORDER_ATOMIC); 
      return 'motorbit.servo(' + Steering + ', ' + degree + ', ' + endDegree + ', speed=' + steeringVelocity + ')\n';
    };
  
      //舵机起始角度和转速
    Blockly.Python.geekServoDegree = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitMagicbit'] = 'import magicbit';
      var code = block.getFieldValue('geekServo');
      var degree = Blockly.Python.valueToCode(this, 'degree', Blockly.Arduino.ORDER_ATOMIC); 
      return 'magicbit.GeekServo(' + code + ',' + degree +  ')\n';
    };
  
    //步进电机28BYJ-48
    Blockly.Python.stepperMotorAngle = function (block) {
      Blockly.Python.definitions_['import_motor'] = 'from microbit import *';
      // Blockly.Python.definitions_['import_microbit'] = 'from Magicbit import *';
      Blockly.Python.definitions_['import_microbitMotor'] = 'import motor';
      Blockly.Python.definitions_['import_microbitMotorInit'] = 'motorbit = motor.init()';
      var angle = block.getFieldValue('angle');
      var stpmAngle = Blockly.Python.valueToCode(this, 'stpmAngle', Blockly.Arduino.ORDER_ATOMIC); 
      return 'motorbit.stepper(' + angle + ', ' + stpmAngle + ')\n';
    };
  
    //步进电机28BYJ-48 圈数
    Blockly.Python.stepperMotorSpeed = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitMotor'] = 'import motor';
      Blockly.Python.definitions_['import_microbitMotorInit'] = 'motorbit = motor.init()';
      var stpm = block.getFieldValue('stpm');
      var motorSpeed = block.getFieldValue('MotorSpeed');
      var result = 360 * motorSpeed;
      return 'motorbit.stepper(' + stpm + ', ' + result + ')\n';
    };
  
    //双步进电机速度
    Blockly.Python.twoStepperMotorAngle = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitMagicbit'] = 'import motor';
      var oneStpmAngle = Blockly.Python.valueToCode(this, 'oneStpmAngle', Blockly.Arduino.ORDER_ATOMIC);
      var twoStpmAngle = Blockly.Python.valueToCode(this, 'twoStpmAngle', Blockly.Arduino.ORDER_ATOMIC);
      return 'motor.stepper(1,' + oneStpmAngle + ')\nmotor.stepper(2,' + twoStpmAngle + ')\n';
    };
  
    //双步进电机前进距离
    Blockly.Python.twoStepperMotorCarForward = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitMagicbit'] = 'import magicbit';
      var distance = Blockly.Python.valueToCode(this, 'distance', Blockly.Arduino.ORDER_ATOMIC); 
      var diameter = Blockly.Python.valueToCode(this, 'diameter', Blockly.Arduino.ORDER_ATOMIC);
      return 'magicbit.StpCarMove(' + distance + ',' + diameter + ')\n';
    };
  
     //步进小车转向角度
     Blockly.Python.twoStepperMotorCarAngleForward = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitMagicbit'] = 'import magicbit';
      var carAngle = Blockly.Python.valueToCode(this, 'carAngle', Blockly.Arduino.ORDER_ATOMIC); 
      var carDistance = Blockly.Python.valueToCode(this, 'carDistance', Blockly.Arduino.ORDER_ATOMIC);
      var carDiameter = Blockly.Python.valueToCode(this, 'carDiameter', Blockly.Arduino.ORDER_ATOMIC);
      return 'motorbit.StpCarTurn(' + carAngle + ',' + carDistance +  ',' + carDiameter +')\n';
    };
  
    //电机速度
    Blockly.Python.motorVelocity = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitMotor'] = 'import motor';
      Blockly.Python.definitions_['import_microbitMotorInit'] = 'motorbit = motor.init()';
      var MotorVal = block.getFieldValue('MotorVal');
      var velocity = Blockly.Python.valueToCode(this, 'velocity', Blockly.Arduino.ORDER_ATOMIC);
      return 'motorbit.dcmotor_run(' + MotorVal + ',' + velocity + ')\n';
    };
  
    //双路电机速度
    Blockly.Python.twoMotorVelocity = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitMotor'] = 'import motor';
      Blockly.Python.definitions_['import_microbitMotorInit'] = 'motorbit = motor.init()';
      var oneMotor = block.getFieldValue('oneMotor');
      var twoMotor = block.getFieldValue('twoMotor');
      var oneMotorVelocity = Blockly.Python.valueToCode(this, 'oneMotorVelocity', Blockly.Arduino.ORDER_ATOMIC);
      var twoMotorVelocity = Blockly.Python.valueToCode(this, 'twoMotorVelocity', Blockly.Arduino.ORDER_ATOMIC);
      return 'motorbit.dcmotor_run(' + oneMotor + ',' + oneMotorVelocity + ')\nmotorbit.dcmotor_run(' + twoMotor + ',' + twoMotorVelocity + ')\n';
    };
  
    //电机速度延时
    Blockly.Python.motorVelocityDelayed = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitMotor'] = 'import motor';
      Blockly.Python.definitions_['import_microbitMotorInit'] = 'motorbit = motor.init()';
      var motorPort = block.getFieldValue('motorPort');
      var motorVelocity1 = Blockly.Python.valueToCode(this, 'motorVelocity1', Blockly.Arduino.ORDER_ATOMIC);
      var motorDelayed = Blockly.Python.valueToCode(this, 'motorDelayed', Blockly.Arduino.ORDER_ATOMIC);
      return 'motorbit.dcmotor_run(' + motorPort + ',' + motorVelocity1 + ')\nsleep('+motorDelayed+')\n';
    };
  
    //电机停止
    Blockly.Python.stopMotor = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitMagicbit'] = 'import motor';
      Blockly.Python.definitions_['import_microbitMotorInit'] = 'motorbit = motor.init()';
      var stopMotor = block.getFieldValue('stopMotor');
      return 'motorbit.dcmotor_stop(' + stopMotor + ')\n';
    };
  
    //停止所有电机
    Blockly.Python.stopAllMotor = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitMotor'] = 'import motor';
      Blockly.Python.definitions_['import_microbitMotorInit'] = 'motorbit = motor.init()';
      return 'motorbit.dcmotor_stop(1)\nmotorbit.dcmotor_stop(2)\nmotorbit.dcmotor_stop(3)\nmotorbit.dcmotor_stop(4)\n';
    };
  
     //读取RGB超声波距离
     Blockly.Python.readRGBDistance = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitNeopixel'] = 'import neopixel';
      Blockly.Python.definitions_['import_microbitIr'] = 'import emakefun_IR';
      var rgbDistance = block.getFieldValue('rgbDistance');
      var value = 'emakefun_IR.get_UTdistance(' + rgbDistance + ')';
      return [value, Blockly.Python.ORDER_ATOMIC];
    };

  //读取RGB超声波距离
   Blockly.Python.motorbit_readRGBDistance = function (block) {
    var rgbDistance = block.getFieldValue('rgbDistance');
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
    Blockly.Python.definitions_['import_microbitUltrasonic'] = 'from sensor import ultrasonic';
    Blockly.Python.definitions_['import_ultrasonicInit'] = 'ultrasonic.init_rus_04('+ rgbDistance + ', pin16)';7
    var value = 'ultrasonic.get_distance()';
    return [value, Blockly.Python.ORDER_ATOMIC];
  };
  
     //RGB超声波传感器模块
  Blockly.Python.motorbit_rgbUltrasonicColor = function(block) {
    var dropdown_rgbLight = this.getFieldValue('rgbLight');
    var dropdown_rgbSpecial = this.getFieldValue('rgbSpecial');
    //rgbPort
    var dropdown_rgbPort = this.getFieldValue('rgbPort');
    // var dropdown_rgbUlr = Blockly.Arduino.valueToCode(this, 'rgbUlr', Blockly.Arduino.ORDER_ATOMIC);
    // var dropdown_rgbUlg = Blockly.Arduino.valueToCode(this, 'rgbUlg', Blockly.Arduino.ORDER_ATOMIC);
    // var dropdown_rgbUlb = Blockly.Arduino.valueToCode(this, 'rgbUlb', Blockly.Arduino.ORDER_ATOMIC);
    var dropdown_rgbUlr = 0;
    var dropdown_rgbUlg = 0;
    var dropdown_rgbUlb = 0;
    var dropdown_rgbBrightness = Blockly.Arduino.valueToCode(this, 'rgbBrightness', Blockly.Arduino.ORDER_ATOMIC);
    Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_neopixel'] = 'import neopixel';
    var color = '';
    var special = "";
    var brightness = "";
    var dropdown_colour = block.childBlocks_[1].colour_;
      var colorStr = dropdown_colour.colorRgb();
      if (colorStr) {
        var colorArr = colorStr.split(",");
        dropdown_rgbUlr = colorArr[0];
        dropdown_rgbUlg = colorArr[1];
         dropdown_rgbUlb = colorArr[2];
     }
    if(dropdown_rgbLight === 'left'){
      color = 'npRgb[0] = ('+dropdown_rgbUlg+', '+ dropdown_rgbUlr +', '+dropdown_rgbUlb+')\nnpRgb[1] = ('+dropdown_rgbUlg+', '+ dropdown_rgbUlr +', '+dropdown_rgbUlb+')\nnpRgb[2] = ('+dropdown_rgbUlg+', '+ dropdown_rgbUlr +', '+dropdown_rgbUlb+')\n'
      + 'npRgb[3] = (0, 0, 0)\nnpRgb[4] = (0, 0, 0)\nnpRgb[5] = (0, 0, 0)\n';
      special = "npRgb."+ dropdown_rgbSpecial +"(0, 2)\n";
      brightness = 'npRgb.brightness(0, 2, '+dropdown_rgbBrightness+')\n' + special;
    }else if(dropdown_rgbLight === 'right'){
      color = 'npRgb[0] = (0, 0, 0)\nnpRgb[1] = (0, 0, 0)\nnpRgb[2] = (0, 0, 0)\n'
      + 'npRgb[3] = ('+dropdown_rgbUlg+', '+ dropdown_rgbUlr +', '+dropdown_rgbUlb+')\nnpRgb[4] = ('+dropdown_rgbUlg+', '+ dropdown_rgbUlr +', '+dropdown_rgbUlb+')\nnpRgb[5] = ('+dropdown_rgbUlg+', '+ dropdown_rgbUlr +', '+dropdown_rgbUlb+')\n';
      special = "npRgb."+ dropdown_rgbSpecial +"(3, 5)\n";
      brightness = 'npRgb.brightness(3, 5, '+dropdown_rgbBrightness+')\n' + special;
    }else{
      color = 'npRgb[0] = ('+dropdown_rgbUlg+', '+ dropdown_rgbUlr +', '+dropdown_rgbUlb+')\nnpRgb[1] = ('+dropdown_rgbUlg+', '+ dropdown_rgbUlr +', '+dropdown_rgbUlb+')\nnpRgb[2] = ('+dropdown_rgbUlg+', '+ dropdown_rgbUlr +', '+dropdown_rgbUlb+')\n'
      +'npRgb[3] = ('+dropdown_rgbUlg+', '+ dropdown_rgbUlr +', '+dropdown_rgbUlb+')\nnpRgb[4] = ('+dropdown_rgbUlg+', '+ dropdown_rgbUlr +', '+dropdown_rgbUlb+')\nnpRgb[5] = ('+dropdown_rgbUlg+', '+ dropdown_rgbUlr +', '+dropdown_rgbUlb+')\n'
      ;
      special = "npRgb."+ dropdown_rgbSpecial +"(0, 5)\n";
      brightness = 'npRgb.brightness(0, 5, '+dropdown_rgbBrightness+')\n' + special;
    }
    Blockly.Python.definitions_['import_portRGB'] = 'npRgb = neopixel.NeoPixel('+ dropdown_rgbPort +', 6)';
    Blockly.Python.definitions_['import_dataRGB'] =  color;
    // Blockly.Python.definitions_['import_brightness'] = brightness;
    return brightness;
  }

  String.prototype.colorRgb = function(){
    var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
    var sColor = this.toLowerCase();
    if(sColor && reg.test(sColor)){
      if(sColor.length === 4){
        var sColorNew = "#";
        for(var i=1; i<4; i+=1){
          sColorNew += sColor.slice(i,i+1).concat(sColor.slice(i,i+1));	
        }
        sColor = sColorNew;
      }
      //处理六位的颜色值
      var sColorChange = [];
      for(var i=1; i<7; i+=2){
        sColorChange.push(parseInt("0x"+sColor.slice(i,i+2)));	
      }
      return  sColorChange.join(",") ;
    }else{
      return sColor;	
    }
  };
    //RGBColor  
    Blockly.Python.RGBColor = function (block) {
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_microbitNeopixel'] = 'import neopixel';
      // Blockly.Python.definitions_['import_microbitIr'] = 'import emakefun_IR';
      var direction = block.getFieldValue('direction');
      // var showColor = block.getFieldValue('showColor');
      // var showColor = Blockly.Python.valueToCode(this, 'showColor', Blockly.Arduino.ORDER_ATOMIC);
      var showColor = Blockly.Python.valueToCode(this, 'showColor', Blockly.Arduino.ORDER_ATOMIC);
  
      var magic = block.getFieldValue('magic');
      // var reg= /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
      console.log("showColor",showColor);
      return 'emakefun_IR.RGB_UT(' + direction + ',' + 1 +','+ magic + ')\n';
    };
  
      //模拟读取引脚
      Blockly.Python.neopixelInit = function (block) {
        var pin = block.getFieldValue('initPort');
        var code = '' + pin + '.read_analog()';
        Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
        Blockly.Python.definitions_['import_neopixel'] = 'import neopixel';
        return [code, Blockly.Python.ORDER_ATOMIC]
      };
  
      Blockly.Python.boardRGB = function (block) {
        Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
        Blockly.Python.definitions_['import_neopixel'] = 'import neopixel';
        Blockly.Python.definitions_['import_port'] = 'np = neopixel.NeoPixel(pin16, 4)';
        Blockly.Python.definitions_['import_array0'] = 'np[0] = (0, 0, 0)';
        Blockly.Python.definitions_['import_array1'] = 'np[1] = (0, 0, 0)';
        Blockly.Python.definitions_['import_array2'] = 'np[2] = (0, 0, 0)';
        Blockly.Python.definitions_['import_array3'] = 'np[3] = (0, 0, 0)';
        return '';
      };
  
      Blockly.Python.boardRGBColor = function (block) {
        var dropdown_boardLight = this.getFieldValue('boardLight');
        var dropdown_boardRgbSpecial = this.getFieldValue('boardRgbSpecial');
        // var dropdown_rgbUlr = Blockly.Arduino.valueToCode(this, 'boardRgbr', Blockly.Arduino.ORDER_ATOMIC);
        // var dropdown_rgbUlg = Blockly.Arduino.valueToCode(this, 'boardRgbg', Blockly.Arduino.ORDER_ATOMIC);
        // var dropdown_rgbUlb = Blockly.Arduino.valueToCode(this, 'boardRgbb', Blockly.Arduino.ORDER_ATOMIC);
        var dropdown_boardRgbBrightness = Blockly.Arduino.valueToCode(this, 'boardRgbBrightness', Blockly.Arduino.ORDER_ATOMIC);
        var array = "import_array"+dropdown_boardLight;
        var dropdown_colour = block.childBlocks_[1].colour_;
        var colorStr = dropdown_colour.colorRgb();
        var red_color = 0;
        var blue_color = 0;
        var green_color = 0; 
        if (colorStr) {
          var colorArr = colorStr.split(",");
          red_color = colorArr[0];
          green_color = colorArr[1];
          blue_color = colorArr[2];
        }
        var boardnp = 'np['+dropdown_boardLight+'] = ('+ red_color + ', '+ green_color + ', ' + blue_color +')';
        var code = boardnp + "np.brightness("+ dropdown_boardLight +","+ dropdown_boardLight +","+dropdown_boardRgbBrightness  +")\nnp."+ dropdown_boardRgbSpecial +"("+dropdown_boardLight+","+dropdown_boardLight+")\n";
        return code;
      };
      
        //magicbit_IR
    Blockly.Python.motorbit_IR = function (block) {
      var dropdown_irPin = this.getFieldValue('irPin');
      var dropdown_microbitIRButton = this.getFieldValue('microbitIRButton');
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_necIr'] = 'from sensor import nec_ir';
      Blockly.Python.definitions_['import_nec_irInit'] = 'nec_ir.init('+ dropdown_irPin +')';
      Blockly.Python.definitions_['codeLine_irData'] = '  key = nec_ir.get_code()';
      var code = "key == " + dropdown_microbitIRButton;
      return [code];
    };

     //magicbit_IR
     Blockly.Python.motorbit_IRValue = function (block) {
      var dropdown_irPin = this.getFieldValue('irPin1');
      // var dropdown_microbitIRButton = this.getFieldValue('microbitIRButton');
      Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
      Blockly.Python.definitions_['import_necIr'] = 'from sensor import nec_ir';
      Blockly.Python.definitions_['import_nec_irInit'] = 'nec_ir.init('+ dropdown_irPin +')';
      var code = "nec_ir.get_code()";
      return [code];
    };


      Blockly.getColorByName2 = function (block, name) {
        const childList = block.inputList;
        const fieldList = block.childBlocks_;
        let colour_ = null;
        console.log(name);
        console.log(Blockly);
        childList.map((v, key) => {
  
            if (v.name === name){
              console.log(v);
                colour_ = fieldList[key].colour_;
            }
        });
        return colour_;
    };
  
      Blockly.Python.neopixelSetColor = function (block) {
        // Blockly.Python.definitions_['import_microbit'] = 'from microbit import *';
        // Blockly.Python.definitions_['import_microbitNeopixel'] = 'import neopixel';
        // // Blockly.Python.definitions_['import_microbitIr'] = 'import emakefun_IR';
        // var direction = block.getFieldValue('direction');
        // var showColor = block.getFieldValue('showColor');
        // var showColor = Blockly.Python.valueToCode(this, 'showColor', Blockly.Arduino.ORDER_ATOMIC);
        // var showColor = Blockly.Python.valueToCode(this, 'setColor', Blockly.Arduino.ORDER_ATOMIC);
        console.log(block);
       
        var color = Blockly.getColorByName2(block,"setColor");
       
        // console.log(block);
        // var code = '\'' + block.getFieldValue('COLOR') + '\'';
        // console.log(showColor);
        console.log(color);
        // var magic = block.getFieldValue('magic');
        // var reg= /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
        // console.log("showColor",showColor);
        return [code, Blockly.Python.ORDER_ATOMIC];
      };
  
  Blockly.Python.math_positive_number = Blockly.Arduino.math_whole_number;

  return Blockly;
}

module.exports = AddMotorbitCode;
